dos71253
2018-10-30 14:18
浏览 341
已采纳

如何将带时区的日期转换为Javascript ISO格式?

I am trying to convert this date string ("2018-10-29T11:48:09.180022-04:00") to ISO format in Go. But not able to do. Can anyone help?

package main

import (
    "fmt"
    "time"
)

func main() {
    l,_ := time.Parse("2006-01-02T15:04:05Z07:00", "2018-10-29T15:18:20-04:00")
    fmt.Println(l, time.Now(), time.Now().UTC().Format("2006-01-02T15:04:05Z07:00"))
}

Output:

2018-10-29 15:18:20 -0400 -0400 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 2009-11-10T23:00:00Z

https://play.golang.org/p/gXw39_Y-hpR

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

我正在尝试转换此日期字符串(“ 2018-10-29T11:48:09.180022-04:00” )转换为Go中的ISO格式。 但是做不到。 有人可以帮忙吗?

包主程序

 导入(
“ fmt” 
“ time” 
)
 
func  main(){
l,_:= time.Parse(“ 2006-01-02T15:04:05Z07:00”,“ 2018-10-29T15:18:20-04:00”)
 fmt.Println(  l,time.Now(),time.Now()。UTC()。Format(“ 2006-01-02T15:04:05Z07:00”))
} 
   
  
 

输出:

 <代码> 2018-10-29 15:18:20 -0400 -0400 2009-11-10 23:00:00 +0000 UTC m =  +0.000000001 2009-11-10T23:00:00Z 
   
 
 

https://play.golang.org/p/gXw39_Y-hpR

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongzha5934 2018-10-30 14:34
    已采纳

    Note that your input string is valid ISO 8601 format.

    However, for JSON serialization, JavaScript uses a slightly different (but still completely valid) style of ISO 8601 date format in which only 3 digits are used for fractional seconds (giving millisecond resolution) and the timezone is adjusted to Coordinated Universal Time (UTC), (aka GMT+0, or "Zulu" timezone) designated with a Z.

    // JavaScript
    JSON.stringify(new Date()); // => "2018-10-30T15:22:30.293Z"
    // Millisecond resolution ─────────────────────────────┺┻┛┃
    // "Zulu" (UTC) time zone ────────────────────────────────┚
    

    You can convert your timestamp into the JavaScript style by first parsing the input string, then converting to Zulu time via the UTC() method, then formatting with the desired output format.

    For example (Go Playground):

    const (
      INPUT_FORMAT  = "2006-01-02T15:04:05.999999999-07:00"
      OUTPUT_FORMAT = "2006-01-02T15:04:05.000Z"
    )
    
    func timestampToJavaScriptISO(s string) (string, error) {
      t, err := time.Parse(INPUT_FORMAT, s)
      if err != nil {
        return "", err
      }
      return t.UTC().Format(OUTPUT_FORMAT), nil
    }
    
    func main() {
      s := "2018-10-29T11:48:09.180022-04:00"
      s2, err := timestampToJavaScriptISO(s)
      if err != nil {
        panic(err)
      }
    
      fmt.Println(s2)
      // 2018-10-29T15:48:09.180Z
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题