you are better than you think

golang时间小结

· by thur · Read in about 1 min · (125 Words)
golang time

1.求前一天的日期(字符串输出)

    now := time.Now()
    yesterday := now.AddDate(0, 0, -1)
    dt := yesterday.Format("20060102")

2.求一天0:00:00到23:59:59 (报表查询)

    now := time.Now()
    yesterday := now.AddDate(0, 0, -1)
    year, month, day := yesterday.Date()
    yesterday_start := time.Date(year, month, day, 0, 0, 0, 0, now.Location())
    yesterday_end := time.Date(year, month, day, 23, 59, 59, 0, now.Location())

3.int64 -> time.Time

秒级别的int64

    t = time.Unix(sec, 0)

毫秒级别的int64

    sec := tm / 1000
    ms := tm % 10000 * 1e6
    t = time.Unix(sec, ms)

4.time.Time -> int64

纳秒数转换

    var t time.Time
    t.UnixNano() / 1e6

5.时间转换为字符串

利用format指定格式,例如: 2016年11月05 10:00:00 -> 20161105100000

df := time.Now().Format("20060102150405")

6.字符串转为时间

func String2Time(s string) (t time.Time, err error) {
    layout := "2006-01-02 15:04:05"
    loc, _ := time.LoadLocation("Asia/Shanghai")
    t, err = time.ParseInLocation(layout, s, loc)
    if err != nil {
        log.Println(s)
    }
    return t, err
}

Comments