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

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

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端