美文网首页
JS 转换日期UTC类型

JS 转换日期UTC类型

作者: Maggieq8324 | 来源:发表于2019-08-26 13:25 被阅读0次

    前台取到的日期类型为UTC,"yyyy-MM-dd'T'HH:mm:ss.SSS",后台接收报错如下:

    org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value 
    of type `java.util.Date` from String "2019-08-10T02:37:54.770Z": not a valid representation 
    (error: Failed to parse Date value '2019-08-10T02:37:54.770Z': Unparseable date: "2019-08-10T02:37:54.770Z");
    nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: 
    Cannot deserialize value of type `java.util.Date` from String "2019-08-10T02:37:54.770Z": 
    not a valid representation (error: Failed to parse Date value '2019-08-10T02:37:54.770Z': Unparseable date: "2019-08-10T02:37:54.770Z")
    

    究其原因为Spring无法将UTC类型的值解析为Date日期格式,解决方法如下:

    formatTime(time, format) {
            var date = new Date(time);
            var formatter = function (i) { return (i < 10 ? '0' : '') + i };
            return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
              switch (a) {
                case 'yyyy':
                  return formatter(date.getFullYear());
                  break;
                case 'MM':
                  return formatter(date.getMonth() + 1);
                  break;
                case 'mm':
                  return formatter(date.getMinutes());
                  break;
                case 'dd':
                  return formatter(date.getDate());
                  break;
                case 'HH':
                  return formatter(date.getHours());
                  break;
                case 'ss':
                  return formatter(date.getSeconds());
                  break;
              }
            })
          }
    

    调用该js方法将相应值转换为Date日期类型:

    formatTime(changeDate,'yyyy-MM-dd HH:mm:ss')
    

    相关文章

      网友评论

          本文标题:JS 转换日期UTC类型

          本文链接:https://www.haomeiwen.com/subject/vbmrectx.html