4

How to convert string to timestamp and date in JS. here am using Date.parse(), but its not working in IE and FF. My code is..

in chrome its working fine.

 var str = "05-Sep-2013 01:05:15 PM ";
 console.log( Date.parse( str ) );  
 console.log( Date.parse( str.replace(/-/g, '/') ) ); // 1378404315000

in IE its returns

 console.log( Date.parse( str.replace(/-/g, '/') ) ); // NaN

Please help me. thanks in advance.

GVR
  • 89
  • 2
  • 8
  • Help you how? What is your question? What do you want to have happen? – Makyen Aug 26 '16 at 06:58
  • 3
    because you can't just throw any old format that Chrome likes at IE and Firefox - Chrome handles dates differently (not more correct or less correct, just different) – Jaromanda X Aug 26 '16 at 06:59
  • @Makye, I have to convert the string to date, for that am using Date.parse(). here am passing my string and converting to time stamp again am converting to date by using Date(). in IE am not able to parse the string. its returning NaN. please help me, thanks in advance. – GVR Aug 26 '16 at 07:04
  • That does not look like a Date in either a RFC2822 / IETF date syntax ([RFC2822 Section 3.3](https://tools.ietf.org/html/rfc2822#section-3.3)) format, e.g. "Mon, 25 Dec 1995 13:30:00 GMT", or a [ISO 8601](http://www.w3.org/TR/NOTE-datetime) format e.g. "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time). Read: [`Date.parse()` (Firefox)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Description) – Makyen Aug 26 '16 at 07:09
  • From what source are you getting the date? – Makyen Aug 26 '16 at 07:09
  • http://stackoverflow.com/questions/39147558/date-parse-is-not-working-in-fire-fox-and-ie-its-working-fine-in-chrome and http://stackoverflow.com/questions/27720916/converting-string-into-date-format-in-js/27721275#27721275 and certainly many more. – Xotic750 Aug 26 '16 at 07:20
  • @Xotic750, your first duplicate uses the *exact* same string, but has no valid answer. Homework question? – Makyen Aug 26 '16 at 07:31
  • Possibly. However, I have linked to all the relevant information on MDN and to another answer on SO that explains how to do it. – Xotic750 Aug 26 '16 at 07:33

3 Answers3

7

don't replace the '-' with '/', use whitespace instead.

var str = "05-Sep-2013 01:05:15 PM ";
console.log( Date.parse( str.replace(/-/g, ' ') ) );

that works for me in IE

have a look at w3schools - they're working with whitespaces :)

Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
Eldo.Ob
  • 774
  • 4
  • 16
0

It is kind of odd, but a working solution for me is-

var str = "05-Sep-2013 01:05:15 PM ";
console.log( Date.parse( str.replace("-", " ") ) );
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
0

This format works with Chrome, Firefox and Safari:

const epochTime = Date.parse('2020/11/24 15:30')
Banzy
  • 1,590
  • 15
  • 14