0

I am trying to create an if statement that can check today's date and time and if it's greater than a predefined date and time, do something. I'm looking to do this in vanilla JS only and get it to work in IE.

This is the basic working code for Chrome.

var ToDate = new Date()

if (new Date("2018-11-30 05:00").getTime() > ToDate.getTime()) {
  alert("true")
} else {
  alert("false")
}

How can I make something like this work in IE?

if (new Date("2018-11-30 05:00").getTime() > ToDate.getTime()) {
GoldenGonaz
  • 1,116
  • 2
  • 17
  • 42

4 Answers4

0

On firefox and chrome there are no issues with it. On Internet Explorer it's false.

On IE (or in general) the string needs to be an RFC2822 or ISO 8601 formatted date

Example:

new Date("2018-11-29T19:15:00.000Z")
Tyr
  • 2,810
  • 1
  • 12
  • 21
0

If you need portable solution (eg. support older Internet Explorer) I would use this constructor instead:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

Keep in mind that monthIndex starts from 0 (January).

Test:

function assertTrue(exp, message) {
   if (exp === false) {
     message = message || 'Assertion failed';
     alert(message);
     throw message;
   }
}

function testShouldPassForDatesInTheFuture() {
    var ToDate = new Date(2018, 10, 29);
    assertTrue(new Date(2018, 10, 30).getTime() > ToDate.getTime());
}

function testShouldPassForDatesInThePast() {
    var ToDate = new Date(2018, 10, 29);
    assertTrue(new Date(2018, 10, 28).getTime() < ToDate.getTime());
}

testShouldPassForDatesInThePast();
testShouldPassForDatesInThePast();
alert('All test passed');
mauron85
  • 1,364
  • 1
  • 14
  • 28
0

You need to append 'T00:00:00.000Z' to your date.

new Date("2018-11-30" + 'T00:00:00.000Z')

Full code is below:

var ToDate = new Date()

if (new Date("2018-11-30" + 'T00:00:00.000Z').getTime() > ToDate.getTime()) {
  alert("true")
} else {
  alert("false")
}
Hamed
  • 1,351
  • 9
  • 23
  • The OP says "*if it's greater than a predefined date and time*", so it's not a simple matter of adding a fixed time string. Also, this treats the date as UTC whereas it's much more common to treat date-only strings as local (although ECMAScript requires YYYY-MM-DD to be treated as UTC, so adding "T00:00:00Z" does nothing, except for Safari, which is another matter…). – RobG Nov 30 '18 at 00:57
  • Adding "T00:00:00Z" is just a way to simply show how we can convert time to UTC. Its easy to substitute it with another time if timing matters otherwise we can have "T00:00:00Z as default. The OP has internet-explorer tag as well so I assumed this is an IE related question. I tested the original code on IE9 as well as modern browsers. IE9 returns correct answer only if I added "T00:00:00Z. – Hamed Nov 30 '18 at 16:35
  • The OP has a string like "2018-11-30 05:00", which should most probably be treated as local, not UTC. The simple solution is to not use the built–in parser. – RobG Nov 30 '18 at 21:38
0

Your issue is that the date format YYYY-MM-DD HH:mm is not supported by ECMAScript, so parsing is implementation dependent. Safari, for example:

new Date("2018-11-30 05:00")

returns an invalid date.

You can first parse the string manually, either with a bespoke function (e.g. How to parse a string into a date object at JavaScript?) or a library, then you can compare the result with new Date() as for Compare two dates with JavaScript.

A simple parse function is not difficult:

/* Parse string in YYYY-MM-DD HH:mm:ss to a Date
 * All parts after YYYY-MM are optional, milliseconds ignored
 */
function parseDate(s) {
  var b = s.split(/\D/);
  return new Date(b[0], b[1]-1, b[2]||1, b[3]||0, b[4]||0, b[5]||0);
}

["2018-11-23 17:23",
 "2019-01",
 "2020-12-31 23:59:59"].forEach(s => {
   console.log(`${s} => ${parseDate(s).toString()}`);
 });

Then you can compare dates using <, <=, > and >=.

In this case, a date like "2018-01-01" will be considered past at any time after 2018-01-01 00:00:00.000.

Alternatively, since the string is similar to ISO 8601 format, you can compare the parts of the string with a similarly formatted string for today:

// Return date string in YYYY-MM-DD HH:mm:ss format
// Only return as many parts as len, or all 6 if missing
function formatDate(d, len) {
  var parts = [d.getFullYear(), '-'+d.getMonth()+1, '-'+d.getDate(), ' '+d.getHours(), ':'+d.getMinutes(), ':'+d.getSeconds()];
  var spacer = ['-','-',' ',':',':'];
  len = len || 6;
  return parts.splice(0, len).join('');
}

['2018-06-30 12:04',
 '2018-10',
 '2018-12-15 03:14:45',
 '2019-01-01',
 '2020-12-15 03:14:45'].forEach(s => {
   console.log(`${s} has passed? ${s < formatDate(new Date(), s.split(/\D/).length)}`);
});

In this case, 2018-01-01 will be equal to any date generated on that day, and "2018-01" will be equal to any date generated in January 2018. It's up to you whether you use < or <= for the comparison.

So you need to consider carefully where you draw the boundary between earlier and later and adjust the logic accordingly.

RobG
  • 142,382
  • 31
  • 172
  • 209