JavaScript date comparison error in IE8

I have a function that converts a date to YYYY-MM-DD from DD / MM / YYYY.

This works in all browsers except IE8, for some reason, when creating a new Date object, it returns NaN.

The main implementation of the code is http://jsfiddle.net/bX83c/1/

var compareDate = function(value){ var dateFragements = value.split('/'); if (dateFragements.length == 3) { var currentDate = new Date(); currentDate.setHours(0, 0, 0, 0); var startDate = new Date(dateFragements[2] + '-' + dateFragements[1] + '-' + dateFragements[0]); if (startDate >= currentDate) { return true; } else { return false; } } } alert(compareDate('17/09/2013')); 
+4
source share
3 answers

Set your date as follows. It will work in all browsers.

 var startDate = new Date(dateFragements[2] , dateFragements[1] , dateFragements[0]); 

There are 4 ways that a Date object can be initialized using a constructor.

 new Date() // current date and time new Date(milliseconds) //milliseconds since 1970/01/01 new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds) 

A string in a Date object does not mean that it will accept all date strings. If you want to give a string as input, give this. (dateFragements [2] + '/' + dateFragements [1] + '/' + dateFragements [0]) ;. ( / as a delimiter). It will be supported in all browsers.

+3
source

IE8 expects '/' as a separator in the date string, so your function crashes. This can be simplified:

 var compareDate = function(value){ var dateFragements = value.split('/'); if (dateFragements.length == 3) { var currentDate = function(){ return (this.setHours(0), this.setMinutes(0), this.setSeconds(0), this); }.call(new Date) ,startDate = new Date([dateFragements[2], dateFragements[1], dateFragements[0]].join('/')); return startDate>=currentDate; } } 
+2
source
 new Date(dateString) 

accepts the following formats (only):

 "October 13, 1975 11:13:00" "October 13, 1975 11:13" "October 13, 1975" 
+1
source

Source: https://habr.com/ru/post/1500684/


All Articles