我想合并兩個字符串的日期:,當日期相同時返回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為了實現(xiàn)這一點,我制作了兩個格式化日期的函數(shù)。 表示帶有小時的日期。 表示不帶小時的字符串日期。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 回答

一只名叫tom的貓
TA貢獻1906條經(jīng)驗 獲得超3個贊

largeQ
TA貢獻2039條經(jīng)驗 獲得超8個贊
鑒于這種情況,您似乎可以進行字符串比較:
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 關(guān)注
- 114 瀏覽
添加回答
舉報
0/150
提交
取消