Go语言学习之time包(获取当前时间戳等)(the way to go)

生命不止,继续 go go go !!!

每种语言都需要对时间进行处理,golang当然也不例外,go语言为我们提供了time package用于各种时间的转换,处理。

Package time provides functionality for measuring and displaying time.

获取当前时间

func Now

func Now() Time

Now returns the current local time.

func (Time) UTC

func (t Time) UTC() Time

UTC returns t with the location set to UTC.

func (Time) Unix

func (t Time) Unix() int64

Unix returns t as a Unix time,the number of seconds elapsed since January 1,1970 UTC.

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano returns t as a Unix time,the number of nanoseconds elapsed since January 1,1970 UTC.

看到Unix和UnixNano的区别了吧,就是精度不同而已:

package main

import (
    "fmt"
    "strconv"
    "time"
)

func main() {
    t := time.Now()
    fmt.Println(t)

    fmt.Println(t.UTC().Format(time.UnixDate))

    fmt.Println(t.Unix())

    timestamp := strconv.FormatInt(t.UTC().UnixNano(), 10)
    fmt.Println(timestamp)
    timestamp = timestamp[:10]
    fmt.Println(timestamp)
}

输出:
2017-06-21 11:52:29.0826692 +0800 CST
Wed Jun 21 03:52:29 UTC 2017
1498017149
1498017149082669200
1498017149

时间格式化字符串转换

func Parse

package main

import (
    "fmt"
    "strconv"
    "time"
)

func main() {
    const longForm = "Jan 2,2006 at 3:04pm (MST)"
    t,_ := time.Parse(longForm,"Jun 21,2017 at 0:00am (PST)")
    fmt.Println(t)

    const shortForm = "2006-Jan-02"
    t,_ = time.Parse(shortForm,"2017-Jun-21")
    fmt.Println(t)

    t,_ = time.Parse("01/02/2006","06/21/2017")
    fmt.Println(t)
    fmt.Println(t.Unix())

    i,err := strconv.ParseInt("1498003200", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)

    var timestamp int64 = 1498003200
    tm2 := time.Unix(timestamp, 0)
    fmt.Println(tm2.Format("2006-01-02 03:04:05 PM"))
    fmt.Println(tm2.Format("02/01/2006 15:04:05 PM"))
}

输出:
2017-06-21 00:00:00 +0000 PST
2017-06-21 00:00:00 +0000 UTC
2017-06-21 00:00:00 +0000 UTC
1498003200
2017-06-21 08:00:00 +0800 CST
2017-06-21 08:00:00 AM
21/06/2017 08:00:00 AM

再看一个例子:

package main

import (
    "fmt"
    "strings"
    "time"
)

func main() {

    var dates [4]time.Time

    dates[0],_ = time.Parse("2006-01-02 15:04:05.000000000 MST -07:00","1609-09-12 19:02:35.123456789 PDT +03:00")
    dates[1],_ = time.Parse("2006-01-02 03:04:05 PM -0700","1995-11-07 04:29:43 AM -0209")
    dates[2],_ = time.Parse("PM -0700 01/02/2006 03:04:05","AM -0209 11/07/1995 04:29:43")
    dates[3],_ = time.Parse("Time:Z07:00T15:04:05 Date:2006-01-02 ","Time:-03:30T19:18:35 Date:2119-10-29")

    defaultFormat := "2006-01-02 15:04:05 PM -07:00 Jan Mon MST"

    formats := []map[string]string{
        {"format": "2006","description": "Year"},{"format": "06",{"format": "01","description": "Month"},{"format": "1",{"format": "Jan",{"format": "January",{"format": "02","description": "Day"},{"format": "2",{"format": "Mon","description": "Week day"},{"format": "Monday",{"format": "03","description": "Hours"},{"format": "3",{"format": "15",{"format": "04","description": "Minutes"},{"format": "4",{"format": "05","description": "Seconds"},{"format": "5",{"format": "PM","description": "AM or PM"},{"format": ".000","description": "Miliseconds"},{"format": ".000000","description": "Microseconds"},{"format": ".000000000","description": "Nanoseconds"},{"format": "-0700","description": "Timezone offset"},{"format": "-07:00",{"format": "Z0700",{"format": "Z07:00",{"format": "MST","description": "Timezone"}}

    for _,date := range dates {
        fmt.Printf("\n\n %s \n",date.Format(defaultFormat))
        fmt.Printf("%-15s + %-12s + %12s \n",strings.Repeat("-", 15), 12), 12))
        fmt.Printf("%-15s | %-12s | %12s \n","Type","Placeholder","Value")
        fmt.Printf("%-15s + %-12s + %12s \n", 12))

        for _,f := range formats {
            fmt.Printf("%-15s | %-12s | %-12s \n",f["description"],f["format"],date.Format(f["format"]))
        }
        fmt.Printf("%-15s + %-12s + %12s \n", 12))
    }
}

time包的一些其他用法

time包很强大,这里不能整个篇幅的进行介绍,可以自己去看官方的文档。

func Date

func Date(year int,month Month,day,hour,min,sec,nsec int,loc *Location) Time

time常用方法

After(u Time) bool
时间类型比较,是否在Time之后

Before(u Time) bool
时间类型比较,是否在Time之前

Equal(u Time) bool
比较两个时间是否相等

IsZero() bool
判断时间是否为零值,如果sec和nsec两个属性都是0的话,则该时间类型为0

Date() (year int,day int)
返回年月日,三个参数

Year() int
返回年份

Month() Month
返回月份.是Month类型

Day() int
返回多少号

Weekday() Weekday
返回星期几,是Weekday类型

ISOWeek() (year,week int)
返回年份,和该填是在这年的第几周.

Clock() (hour,sec int)
返回小时,分钟,秒

Hour() int
返回小时

Minute() int
返回分钟

Second() int
返回秒数

Nanosecond() int
返回纳秒

应用:

package main

import "fmt"
import "time"

func main() {
    p := fmt.Println

    now := time.Now()
    p(now)

    then := time.Date(
        2017, 06, 21, 20, 34, 58, 0,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())

    p(then.Weekday())

    p(then.Before(now))
    p(then.After(now))
    p(then.Equal(now))

    diff := now.Sub(then)
    p(diff)

    p(diff.Hours())
    p(diff.Minutes())
    p(diff.Seconds())
    p(diff.Nanoseconds())

    p(then.Add(diff))
    p(then.Add(-diff))
}

输出: 2017-06-21 13:22:36.5138633 +0800 CST 2017-06-21 20:34:58 +0000 UTC 2017 June 21 20 34 58 0 UTC Wednesday false true false -15h12m21.4861367s -15.205968371305556 -912.3581022783334 -54741.4861367 -54741486136700 2017-06-21 05:22:36.5138633 +0000 UTC 2017-06-22 11:47:19.4861367 +0000 UTC

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


类型转换 1、int转string 2、string转int 3、string转float 4、用户结构类型转换
package main import s "strings" import "fmt" var p = fmt.Println func main() { p("Contains: ", s.Contains("test&quo
类使用:实现一个people中有一个sayhi的方法调用功能,代码如下: 接口使用:实现上面功能,代码如下:
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件信息 4、删除文件,成功返回true,失败返回false
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http://www.golangtc.com/downloadBeego开发文档地址:http://beego.me/docs/intro/ 安装步骤: 一、GO环境安装 二、配置系统变量 三、Beego安装 一、GO环境安装 根
golang获取程序运行路径:
Golang的文档和社区资源:为什么它可以帮助开发人员快速上手?
Golang:AI 开发者的实用工具
Golang的标准库:为什么它可以大幅度提高开发效率?
Golang的部署和运维:如何将应用程序部署到生产环境中?
高性能AI开发:Golang的优势所在
本篇文章和大家了解一下go语言开发优雅得关闭协程的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。1.简介本文将介绍首先为什么需要主...
这篇文章主要介绍了Go关闭goroutine协程的方法,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。1.简介本文将介绍首先为什么需要主动关闭gor...
本篇文章和大家了解一下go关闭GracefulShutdown服务的几种方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。目录Shutdown方法Regi...
这篇文章主要介绍了Go语言如何实现LRU算法的核心思想和实现过程,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。GO实现Redis的LRU例子常
今天小编给大家分享的是Go简单实现多租户数据库隔离的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会...
这篇“Linux系统中怎么安装NSQ的Go语言客户端”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希
本文小编为大家详细介绍“怎么在Go语言中实现锁机制”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么在Go语言中实现锁机制”文章能帮助大家解决疑惑,下面...
今天小编给大家分享一下Go语言中interface类型怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考