Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble converting /Date(####)/ to MM/dd/yyyy local with MomentJS

Using external API that's sending me dates such as:

/Date(1439596800)/

The above date is:

August 30, 2015

Using momentjs like this:

moment("/Date(1439596800)/").format("MM/DD/YYYY");

Gets me this:

01/17/1970

I'm aware that I'm supposed to multiply * 1000 but was hoping there was a specific MomentJS method.

like image 294
user1447679 Avatar asked Feb 02 '26 17:02

user1447679


2 Answers

It's rather simple.

Your API gives a UNIX timestamp - by default, moment(arg) assumes arg is passed as milliseconds since the 1st January 1970.

For converting it, you must first remove the /Date( and )\. I'd use a RegEx that strips all non-digit characters:

myString = myString.replace(/\D/g,'');

This will leave just the numbers. Now, you can run

moment.unix(myString).format("MM/DD/YYYY");

Moment.js Reference for UNIX timestamps

like image 81
Gabriel Tomitsuka Avatar answered Feb 05 '26 06:02

Gabriel Tomitsuka


The timestamp is in seconds rather than seconds and moment() only understands milliseconds. You can use the moment.unix() function

moment.unix("1439596800").format("MM/DD/YYYY"); // returns 08/15/2015

However you'll still need to extract 1439596800 from /Date(1439596800)/, this can be done with a simple regex

moment.unix(/Date\((\d+)\)/.exec(input)[1]).format("MM/DD/YYYY"); 
// returns 08/15/2015
like image 36
Adam Avatar answered Feb 05 '26 07:02

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!