zoukankan      html  css  js  c++  java
  • 随笔:Golang 时间Time

    先了解下time类型:

    type Time struct {

    // sec gives the number of seconds elapsed since

    // January 1, year 1 00:00:00 UTC.

    sec int64

     

    // nsec specifies a non-negative nanosecond

    // offset within the second named by Seconds.

    // It must be in the range [0, 999999999].

    nsec int32

     

    // loc specifies the Location that should be used to

    // determine the minute, hour, month, day, and year

    // that correspond to this Time.

    // Only the zero Time has a nil Location.

    // In that case it is interpreted to mean UTC.

    loc *Location

    }

    对于time.Time类型,我们可以通过使用函数Before,After,Equal来比较两个time.Time时间:

    t1 := time.Now()

    t2 := t1.Add(-1 * time.Minute)

    fmt.Println(t1.Before(t2))

    上面t1是当前时间,t2是当前时间的前一分钟,输出结果:false

    对于两个time.Time时间是否相等,也可以直接使用==来判断:

    t1 := time.Now()

    t2 := t1.Add(-1 * time.Minute)

    fmt.Println(t1 == t2)

     

    我们可以通过IsZero来判断时间Time的零值

    t1.IsZero()

     

    我们常常会将time.Time格式化为字符串形式:

    t := time.Now()

    str_t := t.Format("2006-01-02 15:04:05")

    至于格式化的格式为什么是这样的,已经被很多人吐槽了,但是,这是固定写法,没什么好说的。

    那么如何将字符串格式的时间转换成time.Time呢?下面两个函数会比较常用到:

    A)

    t, _ := time.Parse("2006-01-02 15:04:05", "2017-04-25 09:14:00")

    这里我们发现,t:=time.Now()返回的时间是time.Time,上面这行代码也是time.Time但是打印出来的结果:

    2017-04-25 16:15:11.235733 +0800 CST

    2016-06-13 09:14:00 +0000 UTC

    为什么会不一样呢?原因是 time.Now() 的时区是 time.Local,而 time.Parse 解析出来的时区却是 time.UTC(可以通过 Time.Location() 函数知道是哪个时区)。在中国,它们相差 8 小时。

    所以,一般的,我们应该总是使用 time.ParseInLocation 来解析时间,并给第三个参数传递 time.Local:

    t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2017-04-25 16:14:00", time.Local)

    之前项目中遇到要获取某个时间之前的最近整点时间,这个时候有几种办法:

    t, _ := time.ParseInLocation("2006-01-02 15:04:05", time.Now().Format("2006-01-02 15:00:00"), time.Local)

     

    t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2016-06-13 15:34:39", time.Local)

    t0:=t.Truncate(1 * time.Hour)

     

     

     

     

     

     

  • 相关阅读:
    iOS中静态库的制作——使用创建静态库项目的方式创建静态库
    在Xcode中自定义代码块——快速代码
    在博客园的第一篇博客
    委派
    As I Began to Love Myself
    When you are old
    RESOURCE SUMMARY
    First One
    js 动态生成div显示id
    js 层的显示和隐藏
  • 原文地址:https://www.cnblogs.com/chase-wind/p/6763048.html
Copyright © 2011-2022 走看看