golang中关于time模块的常用方法

在开发的过程中,大家都会使用到golang中的time模块进行一些时间的处理,以及格式化下面我总结了一些time中常用的方法运行就可以使用

package main

import (
	"fmt"
	"time"
)

func main() {
	//	获取当前时间
	now := time.Now()
	fmt.Println(now)
	fmt.Println(now.Year())
	fmt.Println(now.Month())
	fmt.Println(now.Day())
	fmt.Println(now.Hour())
	fmt.Println(now.Minute())
	fmt.Println(now.Second())
	//  通过指定格式将时间格式转换为指定的时间字符串类型
	format1 := now.Format("2006-01-02 15:04:05")
	format2 := now.Format("2006/01/02 15:04:05")
	format3 := now.Format("2006-01-02")
	format4 := now.Format("2006/01/02")
	format5 := now.Format("15:04:05")
	fmt.Println(format1)
	fmt.Println(format2)
	fmt.Println(format3)
	fmt.Println(format4)
	fmt.Println(format5)
	// 获取秒
	fmt.Println(now.Unix())
	// 获取毫秒
	fmt.Println(now.UnixMilli())
	// 获取微妙
	fmt.Println(now.UnixMicro())
	// 获取纳秒
	fmt.Println(now.UnixNano())

	time1 := time.Unix(now.Unix(), 0).Format("2006-01-02 15:04:05")
	time2 := time.UnixMilli(now.UnixMilli()).Format("2006-01-02 15:04:05")
	time3 := time.UnixMicro(now.UnixMicro()).Format("2006-01-02 15:04:05")
	fmt.Println(time1)
	fmt.Println(time2)
	fmt.Println(time3)

	//	进行时间的添加操作, 负数为减少,整数为添加, 可以是小时  天  秒  分钟  年
	NewTime := now.Add(time.Hour * 1)
	fmt.Println(NewTime)

	// 计算两个时间的差
	SubTime := NewTime.Sub(now)
	fmt.Println(SubTime)

	// 计算当前时间与某个时间的差
	fmt.Println(time.Since(NewTime))

	// 判断当前时间是否在某个时间之前
	date := time.Date(2022, 12, 05, 12, 30, 45, 0, time.UTC)
	fmt.Println(now.Before(date))

	//  判断当前时间是否在某个时间之后
	fmt.Println(now.After(date))
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_43022682

你的鼓励是是我前进的动力,谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值