-1

I can get a date string from background, the format is 'Tue Sep 18 14:42:56 SGT 2018'. I want to convert it to milliseconds in JavaScript.

I've already tried Date.parse('Tue Sep 18 14:42:56 SGT 2018'), but it will return NaN

Anybody can help? Appreciated in advance.

Zhang Kai
  • 21
  • 2
  • 1
    Related: [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript) – str Sep 18 '18 at 08:23
  • https://stackoverflow.com/search?q=javascript+date+parse+string – str Sep 18 '18 at 08:24
  • new Date().getTime() – Abin Thaha Sep 18 '18 at 08:26
  • its a invalid date – xkeshav Sep 18 '18 at 08:28
  • hi... there is no day in your date string. Is that intended ? – trk Sep 18 '18 at 08:32
  • 1
    But it works fine `Date.parse('Tue Sep 18 14:42:56 2018 GMT+0800')` or `Date.parse('Tue Sep 18 14:42:56 2018')` –  Sep 18 '18 at 08:37
  • @SarahRiddell Well, you changed the date string. And even with the change, it is still not a date format as per the specification and thus might not work in every browser. – str Sep 18 '18 at 08:40

2 Answers2

1

this is a valid date string that javascript cannot recognize ,tell the backoffice guys change the date format, better way is directly giving you the milliseconds.

Jerry
  • 170
  • 8
1

You can also do a bit of formatting to that string before you parse it. If you split it, you can build a valid format.

var dateString = 'Tue Sep 18 14:42:56 SGT 2018';
var pieces = dateString.split(" ");
var date = new Date(pieces[2]+" "+pieces[1]+" "+pieces[5]+" "+pieces[3]);
date.setHours(date.getHours()-8); // SGT to UTC
console.log(date.toString());

I created a jsbin for you. https://jsbin.com/jugonur/edit?html,js,console,output

See the valid formats here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

unicorn2
  • 844
  • 13
  • 30
  • 1
    The date format you're creating is not a standard format (i.e. one supported by ECMA-262) and you've removed the timezone component. It makes no sense to parse the string to get the date parts, then create another string that must then be parsed again to crate a Date. Just pass the parts directly to the Date constructor. But you still need to resolve the offset. Fortunately, SGT is observed all year round, so -0800 will do the job. – RobG Sep 18 '18 at 09:06
  • Thanks for pointing that out @RobG I added a -8 to the hours. If I understand correctly, using the Date constructor creates a UTC date? – unicorn2 Sep 18 '18 at 10:32