go语言时间日期

package main

import (
	"fmt"
	"time"
	"reflect"
)

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

	// 时间格式化输出(速记口诀:2006年12345->也就是2006一月二日下午三点四分零五秒)
	layout:="2006-01-02 15:04:05"
	fmt.Println(now.Format(layout))
	
	// 类型
	fmt.Println(reflect.TypeOf(now.Format(layout)))
	
	// 字符串转时间对象
	ts := "2026-10-13 10:49:00"
	t1, err := time.Parse(layout, ts) // 按照上面layout格式解析为时间对象
	if err != nil {
		panic(err)
	}
	fmt.Println(t1, reflect.TypeOf(t1))

	// 时区
	loc, err := time.LoadLocation("America/New_York")  // Asia/Shanghai 这个是北京时间
	if err != nil {
		panic(err)
	}
	fmt.Println(now.In(loc), "American-Time")
	
	// 字符串对象切换时区
	loc1, err := time.LoadLocation("Asia/Shanghai")
	tm1, err := time.ParseInLocation(layout, ts, loc1)
	if err != nil {
		panic(err)
	}
	fmt.Println(tm1, reflect.TypeOf(tm1))
	
	// 时间运算
	fmt.Println("Time Calc")
	fmt.Println(now.Add(10 * time.Hour)) // 数量×单位()  -> 现在过去10小时候的时间
	fmt.Println(now.AddDate(0, 10, 1)) // 日期加减(参数是年、月、日) -> 现在过去十个月一天后的日期
	
	// 时间相减->两个时间相减
	tm2 := now.Add(13*time.Minute)
	fmt.Println(now.Sub(tm2))
	
	// 时间比较
	res := now.Equal(tm2) // = 是否等于当前时间(返回布尔值)
	fmt.Println(res)
	
	res = now.After(tm2) // > 是否大于当前时间(返回布尔值)
	fmt.Println(res)
	
	res = now.Before(tm2) // < 是否小于当前时间(返回布尔值)
	fmt.Println(res)

	// 时间戳
	fmt.Println(now.Unix())	// 秒
	fmt.Println(now.UnixMilli())	// 毫秒
	fmt.Println(now.UnixMicro())	// 微妙
	fmt.Println(now.UnixNano())	// 纳秒
	
	// 归纳总结:时间比较也可以用时间戳来比较,返回的是一个数字类型

}
posted @ 2026-10-21 09:03  还在printf  阅读(6)  评论(0)    收藏  举报