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 #求带 python,使用pycharm爬取智联招聘数据资源并保存为Excel文件,同时以图表形式呈现
  • ¥15 学校优化算法怎么样,国内用的多吗?
  • ¥15 微信购物商城购物车的所有功能以及购物车,和首页的搜索功能
  • ¥40 servlet的web程序部署出错
  • ¥50 activiti 新建流程系列问题
  • ¥50 为什么我版本升级之后运行速度变慢5倍??
  • ¥15 如何在gazebo中加载机械臂和机械手
  • ¥15 纯运放实现隔离采样方案设计
  • ¥20 easyconnect无法连接后缀带.com的网站,一直显示找不到服务器ip地址,但是带有数字的网站又是可以连接上的,如何解决
  • ¥15 电脑开机过商标后就直接这样,求解各位