我如何解析" /日期(1459934700000)/"进入JavaScript Date对象?

时间:2016-04-04 07:11:04

标签: jquery date

我试图通过jQuery解析表达为"/Date(1459934700000)/"的日期。我使用这段代码:

new Date(parseInt(myDateString.substr(6)))

并告诉我这个日期:

Sun Apr 26 1970 02:58:20 GMT+0430 (Iran Standard Time)

但我希望得到4/6/2016 12:45:00 PM等日期。

2 个答案:

答案 0 :(得分:1)

您可以使用自己创建自定义功能,如:



var dt = "/Date(1459934700000)/"; // <---- actual date string 
dt = parseInt(dt.slice(6, -2), 10); // extract the date in ms and parsing it back to numbers


function dateConverter(d, sep){
  var d = new Date(d),   // <-------converting it back to a valid date here
      date = d.getDate(),
      month = d.getMonth()+1,
      year = d.getFullYear(),
      hrs = d.getHours(),
      min = d.getMinutes(),
      sec = d.getSeconds(),
      ampm = hrs >= 12 ? " PM" : " AM";
  
  return month+sep+date+sep+year+" "+hrs+":"+min+":"+sec+ampm;
  
}

document.querySelector('pre').innerHTML = dateConverter(dt, '/'); // <---passed the date in ms here
&#13;
<pre></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

var testDate = 'Sun Apr 26 1970 02:58:20 GMT+0430 (Iran Standard Time)';
alert(moment(testDate).format('DD/MM/YYYY hh:mm:ss A')); 
<script src="http://momentjs.com/downloads/moment.min.js"></script>