0

I hardcoded date string in one variable and passing this in new Date()

let hardcoded = "10/4/2018 12:00:00 AM";
console.log($.type(hardcoded)); // String is printing
console.log(hardcoded); // 10/4/2018 12:00:00 AM  is printing
var d = new Date(hardcoded);
console.log(d); // Thu Oct 04 2018 00:00:00 GMT+0530 (India Standard Time)   is printing
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Here in variable 'd' i am getting proper date .. no any issue.

But in below case same string i am getting in convertedDate variable what i hardcode above but its not working ..

let convertedDate = new Date().toLocaleString("en-us", {
  timeZone: 'UTC'
});
console.log($.type(convertedDate)); // String is printing
console.log(convertedDate); // 6/26/2019 12:02:50 PM  is printing
var d = new Date(convertedDate);
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

but here in variable d :- "Invalid date" is coming..

Harish Bagora
  • 686
  • 1
  • 9
  • 26
  • "10/4/2018 12:00:00 AM" is not a format supported by ECMA-262 so parsing is implementation dependent, i.e. you might get the expected date, some other date, or an invalid date. – RobG Jun 26 '19 at 20:16

2 Answers2

0

Try this

var d = new Date(convertedDate.toDateString())

Your passing

6/26/2019, 12:30:57 PM

but Date() is expecting

2019-06-26T11:30:57.000Z

.toDateString() will convert 6/26/2019, 12:30:57 PM to 2019-06-26T11:30:57.000Z

As you are having this problem in IE11, I found this which may cast light on the issue

IE's toLocaleString has strange characters in results

  • I am working on angular 6 , when i am using "convertedDate.toDateString()" then its showing compilation error over there, i think its considering convertedDate as string that's why its showing compilation problem .. – Harish Bagora Jun 26 '19 at 12:39
  • regarding format .. but its working with hardcoded date which i am passing "10/4/2018 12:00:00 AM" – Harish Bagora Jun 26 '19 at 12:41
0

When using the JavaScript Date instance to create new date, the date string given to the date constructor should be an RFC2822 or ISO 8601 formatted date, not local.

So, I suggest you could modify your code as below:

        let convertedDate = new Date();

        var convertedDatestring = convertedDate.toLocaleString("en-us", {
            timeZone: 'UTC'
        });
        console.log($.type(convertedDatestring)); // String is printing
        console.log(convertedDatestring); // ‎‎6‎/‎26‎/‎2019‎ ‎3‎:‎24‎:‎04‎ ‎PM


        var d = new Date(convertedDate.toUTCString());
        console.log(d); //Wed Jun 26 2019 23:24:04 GMT+0800 
Zhi Lv
  • 18,845
  • 1
  • 19
  • 30