在Go中以格式字符串获取当前时间? [英] Get current time as formatted string in Go?

查看:39
本文介绍了在Go中以格式字符串获取当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中获取当前时间戳并将其转换为字符串的最佳方法是什么?我需要日期和时间,例如.YYYYMMDDhhmmss格式.

What's the best way to get the current timestamp in Go and convert to string? I need both date and time in eg. YYYYMMDDhhmmss format.

推荐答案

使用 time.Now() 函数和 time.Format() 方法.

Use the time.Now() function and the time.Format() method.

t := time.Now()
fmt.Println(t.Format("20060102150405"))

打印出 20110504111515 ,或者至少在几分钟前完成.(我在东部夏令时.) constants 在时间包中定义.

prints out 20110504111515, or at least it did a few minutes ago. (I'm on Eastern Daylight Time.) There are several pre-defined time formats in the constants defined in the time package.

您可以使用 time.Now().UTC()如果您希望使用UTC而不是本地时区.

You can use time.Now().UTC() if you'd rather have UTC than your local time zone.

这篇关于在Go中以格式字符串获取当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆