当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go基础编程实践(三)—— 日期和时间

Go基础编程实践(三)—— 日期和时间

2019年07月02日  | 移动技术网IT编程  | 我要评论

日期和时间

package main

import (
    "fmt"
    "time"
)

func main() {
    // 获取当前时间
    current := time.now()
    // 格式化字符串输出
    fmt.println(current.string())

    // format函数格式化输出
    // 无论要格式化什么时间,"2006-01-02 15:04:05"这几个数字固定不变
    fmt.println("mm-dd-yyyy: ", current.format("01-02-2006"))
    fmt.println("hh:mm:ss mm-dd-yyyy:", current.format("15:04:05 01-02-2006"))
    fmt.println("yyyy-dd-mm hh:mm:ss:", current.format("2006-01-02 15:04:05"))

    // 添加日期
    // adddate的三个参数依次为年、月、日
    currentadddate := current.adddate(-1, 1, 0)
    fmt.println(currentadddate)

    // 添加时间
    currentadd := current.add(10 * time.minute)
    fmt.println(currentadd)

    // 获取时间差,利用sub函数或者利用add/adddate函数增加负值
    // date函数参数:年-月-日-时-分-秒-纳秒
    currentsub := current.sub(time.date(2000, 1, 1, 1, 1, 1, 0, time.utc))
    // currentsub :=currentadd.sub(current)
    fmt.println(currentsub)

    // 从字符串解析时间
    str := "2019-06-29t17:17:17.777z"
    layout := "2006-01-02t15:04:05.000z"
    t, err := time.parse(layout, str)
    if err != nil {
        fmt.println(err)
    }
    fmt.println(t)

}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网