dpvmtdu364462 2019-04-11 03:22
浏览 351
已采纳

如何将字符串转换为time.Time

When I try to convert this json to time I gets the error

output:

HERE------------------------------------ 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC

raw:

{
  "tenantID": "9e266e1a750e45f8862e83341a5d0970",
  "startTime": "2019-4-1T11:45:26.371Z",
  "endTime": "2019-4-10T11:45:26.371Z"
}

Controller:

var bodyBytes []byte
raw := make(map[string]interface{})
jsons := make(map[string]interface{})

if h.Ctx.Request.Body != nil {
    bodyBytes, _ = ioutil.ReadAll(h.Ctx.Request.Body)
}

json.Unmarshal(bodyBytes, &raw)

time1, err := time.Parse(time.RFC3339,raw["startTime"].(string));
time2, err := time.Parse(time.RFC3339,raw["endTime"].(string));
fmt.Println("HERE------------------------------------",time1,time2)

usageSingle, err := compute.UsageSingleTenant(raw["tenantID"].(string), time1, time2)
  • 写回答

1条回答 默认 最新

  • douxuelv7755 2019-04-11 03:42
    关注

    You're using RFC3339, which requires time of the form:

    2019-04-01T11:45:26.371Z
    

    not

    2019-4-1T11:45:26.371Z
    

    When I put the zero padding in your code, it worked fine. Or if I didn't specify RFC time and instead used:

    time1, err := time.Parse("2006-2-1T15:04:05.999Z",raw["startTime"].(string));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?