gobyexample-time

来源:https://github.com/xg-wang/gobyexample/tree/master/examples

package main

import (
    "fmt"
    "time"
)

func main() {
    p := fmt.Println

    //得到当前时间
    now := time.Now()
    p(now)

    //通过提供年月日等信息,你可以构建一个`time`。时间总是关联着位置信息,例如时区
    then := time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)
    p(then)

    //可以提取出时间的各个组成部分
    p(then.Year())
    p(then.Month())
    p(then.Day())
    p(then.Hour())
    p(then.Minute())
    p(then.Second())
    p(then.Nanosecond())
    p(then.Location())

    //输出是星期一到日的`Weekday`也是支持的
    p(then.Weekday())

    //这些方法来比较两个时间,分别测试一下是否是之前,之后或者是同一时刻,精确到秒
    p(then.Before(now))
    p(then.After(now))
    p(then.Equal(now))

    //方法`Sub`返回一个`Duration`来表示两个时间点的间隔时间
    diff := now.Sub(then)
    p(diff)

    //计算出不同单位下的时间长度值
    p(diff.Hours())
    p(diff.Minutes())
    p(diff.Seconds())
    p(diff.Nanoseconds())

    //你可以使用`Add` 将时间后移一个时间间隔,或者使用一个`-`来将时间前移一个时间间隔
    p(then.Add(diff))
    p(then.Add(-diff))

}


输出结果:

2018-11-01 10:36:57.7641798 +0800 CST m=+0.006014801
2009-11-17 20:34:58.651387237 +0000 UTC
2009
November
17
20
34
58
651387237
UTC
Tuesday
true
false
false
78486h1m59.112792563s
78486.03308688682
4.709161985213209e+06
2.8254971911279255e+08
282549719112792563
2018-11-01 02:36:57.7641798 +0000 UTC
2000-12-04 14:32:59.538594674 +0000 UTC
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容