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

如何将带时区的日期转换为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

  • 写回答

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条)

报告相同问题?