go语言---时间类型

go语言的时间相关操作

package main

import (
	"fmt"
	"time"
)

// 时间类型

func main() {
	test1()

}

func test1() {
	var t time.Time
	fmt.Println(t)  // 0001-01-01 00:00:00 +0000 UTC, 这是声明Time时候的默认值,没有实际意义

	// 使用time包下的Now()函数获取操作系统当前时间
	fmt.Println("当前时间是: ", time.Now())  // 当前时间是:  2020-03-24 23:18:21.2752622 +0800 CST m=+0.013001501

	// 通过纳秒时间戳创建时间变量time.Unix()
	tN := time.Unix(0, time.Now().UnixNano())
	fmt.Println("纳秒时间戳: ", tN)  		  // 纳秒时间戳:  2020-03-24 23:20:49.8634985 +0800 CST

	// 自己创建指定时间
	tP := time.Date(2020, 03,24,23, 22, 31, 12345, time.Local)  // nsec 纳秒
	fmt.Println("指定创建的时间: ", tP)  // 指定创建的时间:  2020-03-24 23:22:31 +0800 CST

	// 从上面的时间格式中获取到年/月/日/时/分/秒
	fmt.Println("年: ", tP.Year())
	fmt.Println("月: ", tP.Month())
	fmt.Println("日: ", tP.Day())
	fmt.Println("时: ", tP.Hour())
	fmt.Println("分: ", tP.Minute())
	fmt.Println("秒: ", tP.Second())
	fmt.Println("纳秒: ", tP.Nanosecond())

	/*
	年:  2020
	月:  March
	日:  24
	时:  23
	分:  22
	秒:  31
	纳秒:  0
	 */

	// 日期 Date()
	fmt.Println(tP.Date())  // 2020 March 24
	y, m, d := tP.Date()
	fmt.Println("Date()拆分后: ", y, m, d)  // Date()拆分后:  2020 March 24

	// 时间, 时分秒 Clock()
	fmt.Println(tP.Clock())  // 23 22 31

	// 时间戳 Unix()
	// 秒
	fmt.Println(tP.Unix())  // 1585063351  从1970年1月1日0时开始计算的秒数

	// 纳秒
	fmt.Println(tP.UnixNano())  // 1585063351000012345

	// 时间与字符串的转化 Format("2006-01-02 15:04:05",)
	// 注意: 这里的参数必须是2006年1月2日15点04分05秒,格式可以变,但是时间不能变,否则转化出错
	// 1. 时间转化为字符串
	s1 := tP.Format("2006-1-2 14:32:21")   //  2020-3-24 322:1124:243
	s2 := tP.Format("2006-1-2 15:04:05")   //  2020-3-24 23:22:31
	s3 := tP.Format("2006-01-02 15:04:05") //  2020-03-24 23:22:31
	s4 := tP.Format("01 02 2006 15:04:05") //  03 24 2020 23:22:31
	s5 := tP.Format("2006/01/02 15:04:05") //  2020/03/24 23:22:31
	fmt.Println(s1)
	fmt.Println(s2)
	fmt.Println(s3)
	fmt.Println(s4)
	fmt.Println(s5)

	// 2. 字符串转化为时间Parse("2006-01-02 15:04:05", s), 返回值有两个,时间和错误
	// 注意转化的时候,格式要一致,比如18:01:02和18:1:2就不一致
	s6 := "2020/03/24 23:22:31"
	tS, _ := time.Parse("2006/01/02 15:04:05", s6)
	fmt.Println(tS)  // 2020-03-24 23:22:31 +0000 UTC
}
发布了22 篇原创文章 · 获赞 1 · 访问量 1866

猜你喜欢

转载自blog.csdn.net/weixin_42677653/article/details/105106025