go语言碎片整理之 time

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

内容简介:时间和日期是我们编程中经常用到的,本文主要介绍了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

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

查看所有标签

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

深入浅出Struts 2

深入浅出Struts 2

Budi Kuniawan / 杨涛、王建桥、杨晓云 / 人民邮电出版社 / 2009-04 / 59.00元

本书是广受赞誉的Struts 2优秀教程,它全面而深入地阐述了Struts 2的各个特性,并指导开发人员如何根据遇到的问题对症下药,选择使用最合适的特性。作者处处从实战出发,在丰富的示例中直观地探讨了许多实用的技术,如数据类型转换、文件上传和下载、提高Struts 2应用的安全性、调试与性能分析、FreeMarker、Velocity、Ajax,等等。跟随作者一道深入Struts 2,聆听大量来之......一起来看看 《深入浅出Struts 2》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具