Problems converting / Date (####) / to MM / dd / yyyy local with MomentJS
Using an external API sending me dates like:
/Date(1439596800)/
The above date:
August 30, 2015
Using impulses such as:
moment("/Date(1439596800)/").format("MM/DD/YYYY");
Gets this:
01/17/1970
: (
I know I should be multiplying * 1000, but was hoping there was some momentjs method.
Thank you for your help.
source to share
It's pretty simple.
Your API gives a UNIX timestamp - by default moment(arg)
it assumes arg is passed in as milliseconds since Jan 1, 1970.
To convert it, you must first remove /Date(
and )\
. I would use RegEx, which strips out all unrecognized characters:
myString = myString.replace(/\D/g,'');
This will only leave numbers. You can now run
moment.unix(myString).format("MM/DD/YYYY");
source to share
The timestamp is in seconds, not seconds, and moment () only understands milliseconds. You can use moment.unix () function
moment.unix("1439596800").format("MM/DD/YYYY"); // returns 08/15/2015
However, you 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
source to share
The problem is with extra characters. get rid of them first and multiply.
I am using regex to get only numbers from parentheses, avoiding slashes and parses.
var input = "/Date(1439596800)/"
var regex = /\/Date\((\d+)\)\//;
var match = input.match(regex);
if(match){
var stringUnixTs = match[1];
var tsMs = Number(stringUnixTs) * 1000;
var date = new Date(tsMs); // or pass ts directly into moment
} else { }
source to share