drcvvkx914772
2019-02-03 01:38
浏览 1.7k
已采纳

如何将当前时间格式化为YYYY-MM-DDTHH:MM:SSZ

Never tried Go before and currently doing a small project. One of the task is to get current system time and represent it in YYYY-MM-DDT00:00:00Z format. I believe that Z means that time is represented in UTC format but when i looked into db, all timestamps are like this i.e., 2011-11-22T15:22:10Z.

So how can i format like this in Go?

Update I was able to format it using following code

t := time.Now()
fmt.Println(t.Format("2006-01-02T15:04:05Z"))

Now the question remains, what Z signifies here. Should i get UTC Time?

Another question, it looks like that the value i am using to format impacts the output i.e., when i used 2019-01-02T15:04:05Z the output became 2029-02-02T20:45:11Z, why?

图片转代码服务由CSDN问答提供 功能建议

从未尝试过Go,并且目前正在做一个小项目。 任务之一是获取当前系统时间并以 YYYY-MM-DDT00:00:00Z 格式表示。 我相信 Z 表示时间是以UTC格式表示的,但是当我查看db时,所有时间戳都是这样的,即 2011-11-22T15:22:10Z

那么我该如何在Go中格式化?

Update 我能够使用以下代码对其进行格式化

  t:= time.Now()
fmt.Println(t.Format(“ 2006-01-02T15:04:05Z”))
    
 
 

现在问题仍然存在, Z 在这里表示什么。 我应该获得UTC时间吗?

另一个问题,看来我用来格式化的值会影响输出,即当我使用 2019-01-02T15:04:05Z 输出变成 2029-02-02T20:45:11Z ,为什么?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douci1918 2019-02-03 01:52
    已采纳

    Go provides very flexible way to parse the time by example. For this, you have to write the "reference" time in the format of your choice. The reference time is Mon Jan 2 15:04:05 MST 2006. In my case, I used this reference time to parse the Now():

    fmt.Println(time.Now().UTC().Format("2006-01-02T15:04:05Z"))
    
    已采纳该答案
    打赏 评论
  • doupa2871 2019-02-03 06:28

    "If a time is in Coordinated Universal Time (UTC), a "Z" is added directly after the time without a separating space. "Z" is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". Likewise, "14:45:15 UTC" is written as "14:45:15Z" or "144515Z".[16]"

    From https://en.wikipedia.org/wiki/Time_zone#UTC

    // Some valid layouts are invalid time values for time.Parse, due to formats
    // such as _ for space padding and Z for zone information.
    

    and

    // Replacing the sign in the format with a Z triggers
    // the ISO 8601 behavior of printing Z instead of an
    // offset for the UTC zone. Thus:
    //  Z0700  Z or ±hhmm
    //  Z07:00 Z or ±hh:mm
    //  Z07    Z or ±hh
    

    From the source for package time/format.go

    打赏 评论

相关推荐 更多相似问题