0

I am trying to parse this string

"2017-06-01 11:22:20.683"

It is working just fine in Firefox, but return NaN in IE 11
Unfortunately I am unable to modify the source string since its coming from a legacy system.

function myFunction() {
    var d = Date.parse("2017-06-01 11:22:20.683");
    document.getElementById("demo").innerHTML = d;
}
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
  • 2
    Maybe its because its not [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) compliant. Try `"2017-06-01T11:22:20.683"` instead. – Igor Jun 01 '17 at 18:06
  • unfortunately I cannot modify the source. – JavaSheriff Jun 01 '17 at 18:08
  • 1
    Of course you can modify the string, you have it in javascript and can do anything you want to it. To say otherwise is just nonsense. – gforce301 Jun 01 '17 at 18:09
  • cannot modify the source date format, but I can code js/jquery around it to parse it in other ways... – JavaSheriff Jun 01 '17 at 18:09
  • 1
    unfortunately JavaScript dates are a little wonky in some browsers: officially it needs to support ISO8601 (and i think RFC2822 is by convention) [Source: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date), but non-standard formats tend to be browser dependent, as @Dorival mentioned below [MomentJS](https://momentjs.com/) is very commonly used instead of the built in Date because it offers a standard way to represent Datetimes cross browser, and it supports more formats than Date does (it's also pretty good at guessing given a non-standard format) – Patrick Barr Jun 01 '17 at 18:21

4 Answers4

2

Here is the simpliest solution:

function myFunction(dateString) {
    var str = dateString.replace(/^(.*-[0-9][0-9])(\ )([0-9][0-9]\:.*$)/, '$1T$3')
    var d = Date.parse(str);
    document.getElementById("demo").innerHTML = d;
}
Oleg Imanilov
  • 2,591
  • 1
  • 13
  • 26
1

Unfortunately this API is not quite reliable. Edge still gives you a NaN. You have two options though:

1) Use an external library called MomentJS. Very easy to use and have all corner cases implemented. (http://momentjs.com/docs/)

2) Refer to this question to parse it manually: Why does Date.parse give incorrect results?

Hope that helps

Dorival
  • 689
  • 4
  • 18
1

Please do not replace the '-' with '/', use whitespace instead.

var str = "15-Dec-2019 05:25:45 PM ";
console.log( Date.parse( str.replace(/-/g, ' ') ) );

This worked for me in Chrome and Firefox browsers, i hope, this will help you also.

Kamlesh
  • 5,233
  • 39
  • 50
-1
/// Below example will work in All Browser including IE
<script>
 var selected_date = '2019,Apr,05'; // You need to change date format like this
 var parsing_date = Date.parse(selected_date.replace(/^(.*-[0-9][0-9])(\ )([0-9][0-9]\:.*$)/, '$1T$3'));
 alert(parsing_date); 
</script>