• go语言time用法总结


    1. time.Unix()函数返回公元1970年1月,1日,0时,0分,0秒以来的秒数

    代码示例1:

    // UTC时间1970年1月1日0时0分45秒,所以会打印出 t:45
    t, _ := time.ParseInLocation("2006-01-02 15:04:05", "1970-01-01 00:00:45", time.UTC)
    fmt.Println("t:", t.Unix())
    结果如下图:

    代码示例2:

    // 本地时间1970年1月1日8时0分50秒,因为是中国时间是东八区,比UTC时间早8个小时
    // 相当于UTC的"1970-01-01 08:00:50",所以会打印出 t:50
    t, _ := time.ParseInLocation("2006-01-02 15:04:05", "1970-01-01 08:00:50", time.Local)
    fmt.Println("t:", t.Unix())
    结果如下图:

     

    2. time.Time()声明时,若未初始化则表示UTC时间,公元1年,1月,1日,0时,0分,0秒

    代码示例:

    t1 := time.Time{}
    t2 := time.Now()
    t1Second := t1.Unix()
    t2Second := t2.Unix()
    fmt.Printf("t1:%v, t1Second:%v ", t1, t1Second) // UTC时间1970-01-01 08:00:50的秒数为0,所以在此时间之前的为负值,且在int32范围之外
    fmt.Printf("t2:%v, t2Second:%v ", t2, t2Second)
    fmt.Println("t2Second-t1Second=", t2Second-t1Second) // 所以会返回一个超大的值,已超过int32范围
    结果如下图:

     

    3. 秒数转Duration,例如 dur := 2*time.Second + 500*time.Millisecond

    代码示例:

    t1 := time.Now() // 当前时间
    time.Sleep(3 * time.Second) // 休眠3秒
    dur := 2*time.Second + 500*time.Millisecond // 规定间隔:2秒500毫秒
    // 判断间隔时间
    if time.Now().Sub(t1) > dur {
    fmt.Println("sleep over 2.5s")
    }
    结果如下图:

     

    4. time.Duration 转秒数,接示例3:durSec := dur.Seconds(),返回值类型为float64类型

    代码示例:

    dur := 2*time.Second + 500*time.Millisecond
    durSec := dur.Seconds()
    fmt.Println("durSec:", durSec)
    结果如下图:

     

    5. 时间字符串转为本地时间,比如 "2019-03-18 16:31:45"转为本地时间或UTC时间

    代码示例:

    // 解析字符串 "2019-06-18 08:47:50"为本地时间
    t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2019-06-18 08:47:50", time.Local)
    fmt.Println("t:", t)
    结果如下图:

     

    6. 比较两个时间Time是否相等

    代码示例:

    // 解析字符串 "2019-06-18 08:47:50"为本地时间
    t1, _ := time.ParseInLocation("2006-01-02 15:04:05", "2019-06-18 08:47:50", time.Local)
    t2, _ := time.ParseInLocation("2006-01-02 15:04:05", "2019-06-18 08:47:50", time.Local)
    if t1.Equal(t2) {
    fmt.Println("t1 == t2")
    }
    结果如下图:

     

    7. 得到当年,当月,当日,0时,0分,0秒的时间字符串

    代码示例:

    t1 := time.Now() // 2019年6月18日
    curDayStr := t1.Format("2006-01-02 00:00:00") // 固定到天
    curMonthStr := t1.Format("2006-01-00 00:00:00") // 固定到月
    fmt.Printf("curDayStr:%v ", curDayStr)
    fmt.Printf("curMonthStr:%v ", curMonthStr)
    结果如下图:

  • 相关阅读:
    Mac 简单切换jdk版本
    Mac下查看已安装的jdk版本及其安装目录
    MAC 安装telnet
    【转】JDK 内存参数含义
    【Netty4】深入学习Netty
    PAT甲题题解-1124. Raffle for Weibo Followers-模拟,水题
    PAT甲题题解-1060. Are They Equal (25)-字符串处理(科学计数法)
    PAT甲题题解-1061. Dating (20)-字符串处理,水水
    PAT甲题题解-1062. Talent and Virtue (25)-排序水题
    PAT甲题题解-1064. Complete Binary Search Tree (30)-中序和层次遍历,水
  • 原文地址:https://www.cnblogs.com/cxy2020/p/14588274.html
Copyright © 2020-2023  润新知