我想合并两个字符串的日期:,当日期相同时返回true。我想忽略小时。"2021-05-30T15:00:00""2021-05-30""2021-05-30T15:00:00" => 2021-05-30 "2021-05-30" => 2021-05-30 2021-05-30 == 2021-05-30 // true为了实现这一点,我制作了两个格式化日期的函数。 表示带有小时的日期。 表示不带小时的字符串日期。timeParsersimplifyDateconst dateFormat = "2006-01-02T15:04:05"const simpleDateFormat = "2006-01-02"const departureTime = "2021-05-30T15:00:00"const startDate = "2021-05-30"func timeParser(format, value string) time.Time { parsed, err := time.Parse(format, value) if err != nil { fmt.Println("timeParser Error: ", err) } return parsed}func simplifyDate(value string) time.Time { parsed, err := time.Parse(dateFormat, value) parsed.Format(simpleDateFormat) if err != nil { fmt.Println("timeParser Error: ", err) } return parsed}isStartDate := simplifyDate(departureTime) == timeParser(simpleDateFormat, startDate) // return false fmt.Println("simplifyDate(departureTime)", simplifyDate(departureTime)) //2021-05-30 15:00:00 +0000 UTCfmt.Println("timeParser(simpleDateFormat, startDate)", timeParser(simpleDateFormat, startDate)) // 2021-05-30 00:00:00 +0000 UTC在,我尝试按原样将日期格式化为DD-MM-YYYY。但是我得到的日期在末尾有小时和零,如, 。你能指出我做错了什么吗?timeParsersimplifyDatesimpleDateFormat = "2006-01-02"2021-05-30 00:00:00 +0000 UTC2021-05-30 15:00:00 +0000 UTC
2 回答
largeQ
TA贡献2039条经验 获得超7个赞
鉴于这种情况,您似乎可以进行字符串比较:
package main
func compare(s, t string) bool {
if len(s) > 10 {
s = s[:10]
}
if len(t) > 10 {
t = t[:10]
}
return s == t
}
func main() {
for _, each := range []struct {
s, t string
res bool
} {
{"", "", true},
{"", "2021-05-30T15:00:00", false},
{"2021-05-30T15:00:00", "", false},
{"2021-05-30T15:00:00", "2021-05-30", true},
} {
if compare(each.s, each.t) == each.res {
println("pass")
} else {
println("fail")
}
}
}
- 2 回答
- 0 关注
- 84 浏览
添加回答
举报
0/150
提交
取消