~~~
a1:="2017-12-13 21:04:53"
a2:="2017-12-12 21:04:53"
是字符串类型 非time类型
所以我尝试先转换
t,_:= time.Parse("2017-12-13 21:04:53",a1) //在进行对比
不过测试好久没弄好 所以来求助
我程序功能里要对比这2个时间 相差1天就返回false 否则为true的功能。
~~~
```go
package main
import (
"fmt"
"os"
"time"
)
func main() {
a0 := "2017-12-16 21:04:53"
a1 := "2017-12-13 21:04:53"
a2 := "2017-12-12 21:04:53"
var err error
var t0, t1, t2 time.Time
layout := "2006-01-02 15:03:04"
if t0, err = time.Parse(layout, a0); err != nil {
fmt.Errorf("error while parse time:%v\n", err)
os.Exit(1)
}
if t1, err = time.Parse(layout, a1); err != nil {
fmt.Errorf("error while parse time:%v\n", err)
os.Exit(1)
}
if t2, err = time.Parse(layout, a2); err != nil {
fmt.Errorf("error while parse time:%v\n", err)
os.Exit(1)
}
ONE_DAY := time.Hour * 24
fmt.Printf("a0和a1相差大于一天吗? %v\n", t0.Sub(t1) > ONE_DAY)
fmt.Printf("a2和a1相差大于一天吗? %v\n", t2.Sub(t1) > ONE_DAY)
}
```
#4
更多评论
```go
func CompareTime(t1, t2 string) bool {
FORMAT := "2006-01-02 15:04:05"
T1, err := time.Parse(FORMAT, t1)
if err != nil {
panic(err)
}
T2, err := time.Parse(FORMAT, t2)
if err != nil {
panic(err)
}
if T1.Sub(T2).Hours() == 24 {
return true
}
return false
}
```
#1
<a href="/user/hellsam" title="@hellsam">@hellsam</a> 根据你的需要来,有可能需要改成 `xx == 24 || xx == -24`
#2