zoukankan      html  css  js  c++  java
  • Go_21: Golang 中 time 包的使用二

    常量声明:

    const TimeLayout = "2006-01-02 15:04:05"

      这是个奇葩,必须是这个时间点,据说是 go 诞生之日, 记忆方法:6-1-2-3-4-5 

    1. 获取当前时间戳

    func GetCurrentSystemTimestamp() int64 {
        return time.Now().Unix()
    }

    2. 获取当前 string 时间

    func GetCurrentSystemTimeStr() string {
        return time.Now().Format(TimeLayout)
    }

    3. 时间戳 转 string时间格式

    func Timestamp2StandardTimeStr(timestamp int64) string {
        return time.Unix(timestamp, 0).Format(TimeLayout)
    }

    4. string时间 转 时间戳

      这个稍微有点复杂,golang 语言中在进行此项时间转换是,如果直接使用的是 parse 进行格式化,默认会使用 UTC 格式。那么到底什么是 UTC 时间格式呢?

      整个地球分为二十四时区,每个时区都有自己的本地时间。在国际无线电通信场合,为了统一起见,使用一个统一的时间,称为通用协调时(UTC, Universal Time Coordinated)。UTC 与 格林尼治平均时(GMT, Greenwich Mean Time)一样,都与英国伦敦的本地时相同。北京时区是东八区,领先 UTC 八个小时,故如果传入字符串为:2017-11-13 11:14:21,结果会返回 UTC 转换后的时间戳为:1510571661(2017-11-13 19:14:21)。

      要想解决这个问题,需要使用 time 为我们提供的另外一个解析函数:parseInLocaltion

    func TimeStr2Timestamp(timeStr string) int64 {
        // 得到本地时区
        loc, _ := time.LoadLocation("Local")
        // 读取文件中的时间字符串末尾会带有换行符,需要将其去掉否则解析异常
        tm, error := time.ParseInLocation(TimeLayout, strings.Trim(timeStr, "
    "), loc)
        if error != nil {
            log.Fatal(error)
            return 0
        }
        return tm.Unix()
    }
  • 相关阅读:
    DS博客作业02--栈和队列
    DS博客作业03--树
    C博客作业05--指针
    C语言博客作业04--数组
    C博客作业03--函数
    C博客作业02--循环结构
    C博客作业01--分支、顺序结构
    我的第一篇博客作业
    java购物车案例
    第三周-自主学习任务-面向对象基础与类的识别
  • 原文地址:https://www.cnblogs.com/liang1101/p/7828773.html
Copyright © 2011-2022 走看看