Working with Date() in programming is a little tricky so in this post, we will see when the Date() does not work in IE and Safari. Also will learn how to fix it.
- Most languages have come up with some built-in functionality to help with date function.
- JavaScript in particular has lots of useful functions to aid in getting, setting, and outputting dates.
- This simple basic code below works in all browsers because it simply gives the current date-time.
new Date();
Now The Problem
- When it comes to passing and calculating dates using the new Date(), the below code will not work on IE or Safari.
new Date("2020-08-26 12:29:33"); // Firefox also returns ‘Invalid Date’ whereas it works in Chrome. new Date("10-26-2020");
- Here, IE returns ‘NaN’ and Safari returns ‘Invalid Date’ because for some reason, IE and Safari do not support this type of date format “YYYY-MM-DD”.
And the Solution
- So the solution is to pass a valid date format to Date() Object that supports across all browsers.
- The following are some valid date formats:
// yyyy, mm-1, dd new Date(2020, 09, 26); // yyyy, mm-1, dd, hh, mm, ss new Date(2020, 09, 26, 11, 12, 29); // "mm/dd/yyyy" new Date("10/26/2020"); // "mm/dd/yyyy hh:mm:ss" new Date("10/26/2020 12:29:29"); // milliseconds new Date(1608921000000); // "Day Month dd yyyy hh:mm:ss GMT" new Date("Sat Dec 26 2020 11:12:29 GMT");
I hope this helps you understand and fix the Date() format issue with IE and Safari.
References
- http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari
- https://www.coditty.com/code/javascript-new-date-not-working-on-ie-and-safari
- https://stackoverflow.com/questions/6427204/date-parsing-in-javascript-is-different-between-safari-and-chrome
- https://stackoverflow.com/questions/4310953/invalid-date-in-safari/5646753
Related Posts
Visit https://techtalkbook.com to find more related topics.
Happy Coding!!!