最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert Microsoft JSON Date to Local DateTime Using Moment JS Only - Stack Overflow

programmeradmin1浏览0评论

JSON Date: '/Date(1373428800000)/' End Result: 7/9/2013 8:00 PM EST

Currently I do it in 3 steps:

var a = cleanJsonDate('JsonDate');
var b = formatDate(a); // 7/10/2013 12:00 AM
var c = moment.utc(b); // 7/9/2013 8:00 PM
return c;

Is it possible to accomplish the same result using moment js only?

----Update-----

Combining @ThisClark & @Matt answers. I came as close as possible to the goal; however, the 'h' format does not work for some reason, I still get 20.00.00 instead of 8:00

var m = moment.utc(moment('/Date(1373428800000)/').format('M/D/YYYY h:m A')).toDate();
alert(m);
<script src=".min.js"></script>

JSON Date: '/Date(1373428800000)/' End Result: 7/9/2013 8:00 PM EST

Currently I do it in 3 steps:

var a = cleanJsonDate('JsonDate');
var b = formatDate(a); // 7/10/2013 12:00 AM
var c = moment.utc(b); // 7/9/2013 8:00 PM
return c;

Is it possible to accomplish the same result using moment js only?

----Update-----

Combining @ThisClark & @Matt answers. I came as close as possible to the goal; however, the 'h' format does not work for some reason, I still get 20.00.00 instead of 8:00

var m = moment.utc(moment('/Date(1373428800000)/').format('M/D/YYYY h:m A')).toDate();
alert(m);
<script src="http://momentjs.com/downloads/moment.min.js"></script>

Share Improve this question edited May 18, 2015 at 18:17 usefulBee asked May 15, 2015 at 18:53 usefulBeeusefulBee 9,69210 gold badges52 silver badges95 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

This format is already supported natively by moment.js. Just pass it directly.

moment('/Date(1373428800000)/')

You can then use any of the moment functions, such as .format() or .toDate()

If you want UTC, then do:

moment.utc('/Date(1373428800000)/')

Again, you can call format or toDate, however be aware that toDate will produce a Date object, which will still have local time behaviors. Unless you absolutely need a Date object, then you should stick with format and other moment functions.

I don't see all your code, but if you can just get the value of milliseconds as 1373428800000 out of that json, then you can pass it to moment directly. I think formatDate is a function you wrote. Does it do something important like manipulate time that you require of moment.js, or could you just use the format function of moment?

var date = 1373428800000;
var m = moment.utc(date);
//var m = moment.utc(date).format('M/D/YYYY H:mm A'); <-- alternative format
alert(m);
<script src="http://momentjs.com/downloads/moment.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论