go语言碎片整理之 time

栏目: Go · 发布时间: 5年前

内容简介:时间和日期是我们编程中经常用到的,本文主要介绍了Go语言内置的time包的基本用法。单行导入多行导入

时间和日期是我们编程中经常用到的,本文主要介绍了 Go 语言内置的time包的基本用法。

Go语言中导入包

单行导入

import "time"
import "fmt"

多行导入

import (
    "fmt"
        "time"
)

time包

time.Time类型表示时间。

func main(){
    now := time.Now()
    fmt.Printf("current time is :%v\n",now)
    year := now.Year()
    month := now.Month()
    day := now.Day()
    hour := now.Hour()
    minute:= now.Minute()
    second := now.Second()
    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n",year,month,day,hour,minute,second)
}

时间戳

时间戳是自1970年1月1日(08:00:00GMT)至当前时间的总毫秒数。它也被为Unix时间戳。

func timestampDemo() {
    now := time.Now()            //获取当前时间
    timestamp1 := now.Unix()     //时间戳
    timestamp2 := now.UnixNano() //纳秒时间戳
    fmt.Printf("current timestamp1:%v\n", timestamp1)
    fmt.Printf("current timestamp2:%v\n", timestamp2)
}

使用time.Unix()函数将时间戳转为时间格式。

func timestampDemo2(timestamp int64) {
    timeObj := time.Unix(timestamp, 0) //将时间戳转为时间格式
    fmt.Println(timeObj)
    year := timeObj.Year()     //年
    month := timeObj.Month()   //月
    day := timeObj.Day()       //日
    hour := timeObj.Hour()     //小时
    minute := timeObj.Minute() //分钟
    second := timeObj.Second() //秒
    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

定时器

使用time.Tick(时间间隔),来设置定时器。

func tickDemo(){
    ticker := time.Tick(time.Second)
    for i:=range ticker{
        fmt.Println(i)
    }

}

时间间隔

Duration类型代表两个时间点之间经过的时间,以纳秒为单位。可表示的最长时间段大约为290年。定义时间间隔常量如下:

const (
    Nanosecond Duration =1
        Microsecond               =1000*Nanosecond
        Millisecond                  =1000*Microsecond
        Second                        =1000*Millisecond
        Minute                         =60*Second
        Hour                            =60*Minute
)

例如:time.Duration 表示1纳秒,time.Second表示1秒。

时间加时间间隔

我们在日常的编码过程中可能会遇到要求时间+时间间隔的需求,Go语言的时间对象有提供Add方法如下:

func (t Time) Add(d Duration) Time

举个例子,求一个小时之后的时间:

func main(){
    now := time.Now()
    later := now.Add(time.Hour)
    fmt.Println(later)
}

两个时间相减

求两个时间之间的差值:

func (t Time) Sub(u time) Duration

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Programming in Java

Introduction to Programming in Java

Robert Sedgewick、Kevin Wayne / Addison-Wesley / 2007-7-27 / USD 89.00

By emphasizing the application of computer programming not only in success stories in the software industry but also in familiar scenarios in physical and biological science, engineering, and appli......一起来看看 《Introduction to Programming in Java》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

URL 编码/解码
URL 编码/解码

URL 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具