Search code examples
javascriptmomentjsunix-timestampepoch

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.


Solution

  • 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