开发者社区> 问答> 正文

JS 的时间格式与JSON时间格式如何互相转换?

var myDate = new Date();
myDate.toLocaleString( );

类似这种获取当前时间的JS格式,怎么转换成json格式?
或者怎么把json的时间格式转换成JS格式。
我这里主要做的是要获取当前时间与json格式的截止时间的时间差

展开
收起
小旋风柴进 2016-03-09 13:08:42 3819 0
2 条回答
写回答
取消 提交回答
  • 推荐通过 Moment.js(https://momentjs.com/) 来处理

    2019-07-17 18:55:50
    赞同 展开评论 打赏
  • JSON格式:

    "drvierDate":{"date":9,"day":6,"hours":16,"minutes":30,"month":7,"nanos":0,"seconds":0,"time":1407573000000,"timezoneOffset":-480,"year":114}
    
      toDate(drvierDate)
    
    [javascript] view plain copy
    function toDate(obj){  
         var date = new Date();  
         date.setTime(obj.time);  
         date.setHours(obj.hours);  
         date.setMinutes(obj.minutes);  
         date.setSeconds(obj.seconds);  
         return date.format("yyyy-MM-dd hh:mm:ss"); //调用<span style="font-family: Arial, Helvetica, sans-serif;">Date.prototype.format方法  
    </span>}   
    
    
    [javascript] view plain copy
    Date.prototype.format = function(format) {  
     /*  
    [javascript] view plain copy
     * 时间格式  
      * format="yyyy-MM-dd hh:mm:ss";   
      */  
     var o = {  
      "M+" : this.getMonth() + 1,  
      "d+" : this.getDate(),  
      "h+" : this.getHours(),  
      "m+" : this.getMinutes(),  
      "s+" : this.getSeconds(),  
      "q+" : Math.floor((this.getMonth() + 3) / 3),  
      "S" : this.getMilliseconds()  
     }  
     if (/(y+)/.test(format)) {  
      format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4  
          - RegExp.$1.length));  
     }  
     for (var k in o) {  
      if (new RegExp("(" + k + ")").test(format)) {  
       format = format.replace(RegExp.$1, RegExp.$1.length == 1  
           ? o[k]  
           : ("00" + o[k]).substr(("" + o[k]).length));  
      }  
     }  
     return format;  
    }   
    2019-07-17 18:55:50
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript面向对象的程序设计 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载