golang中time包之时间间隔格式化和秒、毫秒、纳秒等时间戳格式输出的方法实例

 更新时间:2022年08月09日 11:02:56   作者:玉梅小洋  
时间和日期是我们编程中经常会用到的,下面这篇文章主要给大家介绍了关于golang中time包之时间间隔格式化和秒、毫秒、纳秒等时间戳格式输出的方法实例,需要的朋友可以参考下

获取当前时间的年、月、日、时、分、秒的方法如下:

	// 获取当前时间
	now := time.Now()

	// 当前时间的年、月、日、小时、分钟、秒和纳秒都可以通过现有接口直接获取
	year := now.Year()
	month := now.Month()
	day := now.Day()
	hour := now.Hour()
	minute := now.Minute()
	second := now.Second()
	nanosecond := now.Nanosecond()

	// 当前时间的微秒和毫秒是通过纳秒计算生成
	microsecond := nanosecond / 1e3
	millisecond := nanosecond / 1e6

	fmt.Println(now.Format("2006-01-02 15:04:05.000000000"))
	fmt.Println(year, month, day, hour, minute, second, nanosecond, microsecond, millisecond)

运行结果如下:

# 当前时间格式输出
2022-06-09 19:25:52.022598620
2022 June 9 19 25 52 22598620 22598 22

获取从1970到现在经过的时间的方法如下:

	// 获取从1970经过的时间,秒和纳秒都可以通过现有接口直接获取
	sec := now.Unix()     // 时间戳位数为10
	ms := now.UnixMilli() // 时间戳位数为13
	us := now.UnixMicro() // 时间戳位数为16
	ns := now.UnixNano()  // 时间戳位数为19
	fmt.Printf("sec:%v\n ms:%v\n us:%v\n ns:%v\n", sec, ms, us, ns)

运行结果如下:

# 1970经过的时间格式输出
sec:1654773952
 ms:1654773952022
 us:1654773952022598
 ns:1654773952022598620

时间间隔格式化输出方法

	// 时间间隔返回的是time.Duration,下面以1h1m1s1ms1us1ns的时间间隔举例,测试各种格式的打印效果
	duration := 1*time.Hour + 1*time.Minute + 1*time.Second +
		1*time.Millisecond + 1*time.Microsecond + 1*time.Nanosecond
	// 直接使用%v打印,不转换sec、ms或其他。
	fmt.Printf("duration:%v\n", duration)
	fmt.Printf("duration:%6v\n", duration)
	fmt.Printf("duration:%.6v\n", duration)
	fmt.Printf("duration:%.3v\n", duration)

	// duration支持Hours()、 Minutes()、Seconds() 和
	// Milliseconds()、Microseconds()、Nanoseconds()接口
	// 前三个接口返回类型为float64可以通过0.3f打印小数点后的数,
	// 后三个为int64,是整数,小数点后都是0
	// 下面列举秒和毫秒的格式打印,其他时间单位可以参考秒和毫秒

	// 秒的打印格式%f可以打印小数点后9位,精确到纳秒
	fmt.Printf("duration:%vsec\n", duration.Seconds())
	fmt.Printf("duration:%0.3fsec\n", duration.Seconds())
	fmt.Printf("duration:%0.6fsec\n", duration.Seconds())

	// 毫秒没有小数点,都是整数,转换成float后,小数点后都是0
	fmt.Printf("duration:%vms\n", duration.Milliseconds())
	fmt.Printf("duration:%.3dms\n", duration.Milliseconds())
	fmt.Printf("duration:%.3fms\n", float64(duration.Milliseconds()))
}

行结果如下:

# 1h1m1s1ms1us1ns的时间间隔举例格式输出
# %v没有单位转换的时间输出
duration:1h1m1.001001001s
duration:1h1m1.001001001s
duration:1h1m1.
duration:1h1

# 秒的格式输出
duration:3661.001001001sec
duration:3661.001sec
duration:3661.001001sec

# 毫秒的格式输出
duration:3661001ms
duration:3661001ms
duration:3661001.000ms

通过测试程序可以看到:

1.没时间单位转换的格式输出,直接用%v能精确到ns,%.3V,只是对输出的字符串进行了切割。此处建议直接用%v即可。

2.对于秒的格式输出,%v精确到小数点9位,即纳秒。当然可以根据%f的格式调整,例如%.3f精确到毫秒

3.对于毫秒的格式输出,直接用%v或%d即可,转换成float64没有意义

一般在统计一个函数或一段程序运行了多长时间,一般建议使用第二种方式,转换成秒的格式输出,再根据精度调整%f的格式即可。

第一种方式有可能出现时间单位不统一,例如一个是分钟,一个是秒。

上面例子完成的代码如下:

package main

import (
	"fmt"
	"time"
)

func main() {
	// 获取当前时间
	now := time.Now()

	// 当前时间的年、月、日、小时、分钟、秒和纳秒都可以通过现有接口直接获取
	year := now.Year()
	month := now.Month()
	day := now.Day()
	hour := now.Hour()
	minute := now.Minute()
	second := now.Second()
	nanosecond := now.Nanosecond()

	// 当前时间的微秒和毫秒是通过纳秒计算生成
	microsecond := nanosecond / 1e3
	millisecond := nanosecond / 1e6

	fmt.Println(now.Format("2006-01-02 15:04:05.000000000"))
	fmt.Println(year, month, day, hour, minute, second, nanosecond, microsecond, millisecond)

	// 获取从1970经过的时间,秒和纳秒都可以通过现有接口直接获取
	sec := now.Unix()     // 时间戳位数为10
	ms := now.UnixMilli() // 时间戳位数为13
	us := now.UnixMicro() // 时间戳位数为16
	ns := now.UnixNano()  // 时间戳位数为19
	fmt.Printf("sec:%v\n ms:%v\n us:%v\n ns:%v\n", sec, ms, us, ns)


	// 时间间隔返回的是time.Duration,下面以1h1m1s1ms1us1ns的时间间隔举例,测试各种格式的打印效果
	duration := 1*time.Hour + 1*time.Minute + 1*time.Second +
		1*time.Millisecond + 1*time.Microsecond + 1*time.Nanosecond
	// 直接使用%v打印,不转换sec、ms或其他。
	fmt.Printf("duration:%v\n", duration)
	fmt.Printf("duration:%6v\n", duration)
	fmt.Printf("duration:%.6v\n", duration)
	fmt.Printf("duration:%.3v\n", duration)

	// duration支持Hours()、 Minutes()、Seconds() 和
	// Milliseconds()、Microseconds()、Nanoseconds()接口
	// 前三个接口返回类型为float64可以通过0.3f打印小数点后的数,
	// 后三个为int64,是整数,小数点后都是0
	// 下面列举秒和毫秒的格式打印,其他时间单位可以参考秒和毫秒

	// 秒的打印格式%f可以打印小数点后9位,精确到纳秒
	fmt.Printf("duration:%vsec\n", duration.Seconds())
	fmt.Printf("duration:%0.3fsec\n", duration.Seconds())
	fmt.Printf("duration:%0.6fsec\n", duration.Seconds())

	// 毫秒没有小数点,都是整数,转换成float后,小数点后都是0
	fmt.Printf("duration:%vms\n", duration.Milliseconds())
	fmt.Printf("duration:%.3dms\n", duration.Milliseconds())
	fmt.Printf("duration:%.3fms\n", float64(duration.Milliseconds()))
}

下面是时间间隔的时间单位转换的源码:

// time.go

// Nanoseconds returns the duration as an integer nanosecond count.
func (d Duration) Nanoseconds() int64 { return int64(d) }

// Microseconds returns the duration as an integer microsecond count.
func (d Duration) Microseconds() int64 { return int64(d) / 1e3 }

// Milliseconds returns the duration as an integer millisecond count.
func (d Duration) Milliseconds() int64 { return int64(d) / 1e6 }

// These methods return float64 because the dominant
// use case is for printing a floating point number like 1.5s, and
// a truncation to integer would make them not useful in those cases.
// Splitting the integer and fraction ourselves guarantees that
// converting the returned float64 to an integer rounds the same
// way that a pure integer conversion would have, even in cases
// where, say, float64(d.Nanoseconds())/1e9 would have rounded
// differently.

// Seconds returns the duration as a floating point number of seconds.
func (d Duration) Seconds() float64 {
	sec := d / Second
	nsec := d % Second
	return float64(sec) + float64(nsec)/1e9
}

// Minutes returns the duration as a floating point number of minutes.
func (d Duration) Minutes() float64 {
	min := d / Minute
	nsec := d % Minute
	return float64(min) + float64(nsec)/(60*1e9)
}

// Hours returns the duration as a floating point number of hours.
func (d Duration) Hours() float64 {
	hour := d / Hour
	nsec := d % Hour
	return float64(hour) + float64(nsec)/(60*60*1e9)
}

补充:如果想格式化为12小时方式,需指定PM

func formatDemo() {
    now := time.Now()
    // 格式化的模板为Go的出生时间2006年1月2号15点04分 Mon Jan
    // 24小时制
    fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))
    // 12小时制
    fmt.Println(now.Format("2006-01-02 03:04:05.000 PM Mon Jan"))
    fmt.Println(now.Format("2006/01/02 15:04"))
    fmt.Println(now.Format("15:04 2006/01/02"))
    fmt.Println(now.Format("2006/01/02"))
}

总结

到此这篇关于golang中time包之时间间隔格式化和秒、毫秒、纳秒等时间戳格式输出的文章就介绍到这了,更多相关golang time包时间间隔格式化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • golang metrics各个指标含义讲解说明

    golang metrics各个指标含义讲解说明

    这篇文章主要为大家介绍了golang metrics各个指标含义讲解说明,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • 一文带你了解Golang中interface的设计与实现

    一文带你了解Golang中interface的设计与实现

    本文就来详细说说为什么说 接口本质是一种自定义类型,以及这种自定义类型是如何构建起 go 的 interface 系统的,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-01-01
  • Golang依赖注入工具digo的使用详解

    Golang依赖注入工具digo的使用详解

    这篇文章主要为大家详细介绍了Golang中依赖注入工具digo的使用,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-06-06
  • Go语言指针用法详解

    Go语言指针用法详解

    Go指针和C指针在许多方面非常相似,但其中也有一些不同。本文详细讲解了Go语言指针的用法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • golang grpc 负载均衡的方法

    golang grpc 负载均衡的方法

    这篇文章主要介绍了golang grpc 负载均衡的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • Go每日一库之zap日志库的安装使用指南

    Go每日一库之zap日志库的安装使用指南

    这篇文章主要为大家介绍了Go每日一库之zap安装使用示例学习,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • 深入了解Golang的map增量扩容

    深入了解Golang的map增量扩容

    这篇文章主要介绍了深入了解Golang的map增量扩容,扩容的主要目的是为了缩短map容器的响应时间。增量扩容的本质其实就是将总的扩容时间分摊到了每一次hash操作上,更多相关内容需要的小伙伴可以参考一下
    2022-06-06
  • 深入解析Go语言中HTTP请求处理的底层实现

    深入解析Go语言中HTTP请求处理的底层实现

    本文将详细介绍 Go 语言中 HTTP 请求处理的底层机制,包括工作流程、创建 Listen Socket 监听端口、接收客户端请求并建立连接以及处理客户端请求并返回响应等,需要的朋友可以参考下
    2023-05-05
  • Go Java算法之二叉树的所有路径示例详解

    Go Java算法之二叉树的所有路径示例详解

    这篇文章主要为大家介绍了Go Java算法之二叉树的所有路径示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • Go语言实现Snowflake雪花算法

    Go语言实现Snowflake雪花算法

    雪花算法产生的背景当然是twitter高并发环境下对唯一ID生成的需求,得益于twitter内部牛的技术,雪花算法能够流传于至今并且被广泛使用,本文就详细的介绍一下,感兴趣的可以了解一下
    2021-06-06

最新评论