2025年3月15日 星期六 甲辰(龙)年 月十四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Go语言

Go - 获取当前时间 时间格式的转换 秒、毫秒、纳秒时间戳输出

时间:08-18来源:作者:点击数:24

1. Go时间格式的转换

  • package main
  • import (
  • "fmt"
  • "time"
  • )
  • func main() {
  • t := time.Now() //2019-07-31 13:55:21.3410012 +0800 CST m=+0.006015601
  • fmt.Println(t.Format("20060102150405"))
  • //当前时间戳
  • t1 := time.Now().Unix() //1564552562
  • fmt.Println(t1)
  • //时间戳转化为具体时间
  • fmt.Println(time.Unix(t1, 0).String())
  • //基本格式化的时间表示
  • fmt.Println(time.Now().String()) //2019-07-31 13:56:35.7766729 +0800 CST m=+0.005042501
  • fmt.Println(time.Now().Format("2006-01-02")) //2019-07-31
  • fmt.Println(time.Now().Format("2006-01-02 15:04:05")) //2019-07-31 13:57:52
  • //获取第几周
  • _, week := time.Now().ISOWeek()
  • //获取年、月、日
  • year, month, day := rwTools.DateYmdInts()
  • }
  • // 时间戳转年月日 时分秒
  • func DateFormat(timestamp int) string {
  • tm := time.Unix(int64(timestamp), 0)
  • return tm.Format("2006-01-02 15:04")
  • }
  • //时间戳转年月日
  • func DateFormatYmd(timestamp int) string {
  • tm := time.Unix(int64(timestamp), 0)
  • return tm.Format("2006-01-02")
  • }
  • //获取当前年月
  • func DateYmFormat() string {
  • tm := time.Now()
  • return tm.Format("2006-01")
  • }
  • //获取年月日时分秒(字符串类型)
  • func DateNowFormatStr() string {
  • tm := time.Now()
  • return tm.Format("2006-01-02 15:04:05")
  • }
  • //时间戳
  • func DateUnix() int {
  • t := time.Now().Local().Unix()
  • return int(t)
  • }
  • //获取年月日时分秒(time类型)
  • func DateNowFormat() time.Time {
  • tm := time.Now()
  • return tm
  • }
  • //获取第几周
  • func DateWeek() int {
  • _, week := time.Now().ISOWeek()
  • return week
  • }
  • //获取年、月、日
  • func DateYMD() (int,int, int) {
  • year, month, day := DateYmdInts()
  • return year,month,day
  • }
  • // 获取年月日
  • func DateYmdFormat() string {
  • tm := time.Now()
  • return tm.Format("2006-01-02")
  • }
  • // 获取日期的年月日
  • func DateYmdInts() (int, int, int) {
  • timeNow := time.Now()
  • year, month, day := timeNow.Date()
  • return year, int(month), day
  • }

2.golang的time包:秒、毫秒、纳秒时间戳输出

时间戳

10位数的是以 秒 为单位;

13位数的是以 毫秒 为单位;

19位数的是以 纳秒 为单位;

  • package main
  • import (
  • "time"
  • "fmt"
  • )
  • func main() {
  • fmt.Printf("时间戳(秒):%v;\n", time.Now().Unix())
  • fmt.Printf("时间戳(纳秒):%v;\n",time.Now().UnixNano())
  • fmt.Printf("时间戳(毫秒):%v;\n",time.Now().UnixNano() / 1e6)
  • fmt.Printf("时间戳(纳秒转换为秒):%v;\n",time.Now().UnixNano() / 1e9)
  • }
  • """
  • 输出结果
  • 时间戳(秒):1530027865;
  • 时间戳(纳秒):1530027865231834600;
  • 时间戳(毫秒):1530027865231;
  • 时间戳(纳秒转换为秒):1530027865;
  • """
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐