简体   繁体   中英

Convert Microsoft JSON Date to Local DateTime Using Moment JS Only

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM