2

I am trying to check if a specific ISO DateTime is before 18:00

This is the simple code:

   // Define the date I want to check
    var targetDate = "2015-02-04T13:30:00Z";
    // Parse the string into a date object
    var target = new Date.parse(targetDate);
    // Compare the target date againt a new date object set to 18:00:00
    if(target < new Date().setHours(18 , 0, 0)){
        console.log("BEFORE");
    } else {
        console.log("AFTER");
    }

even though the time in my targetDate is set to 13:30:00 the output is always AFTER.

I have search how to compare times, and from the results I found, a simple comparison as I did should work.

I would really appreciate it if someone could point out what I am doing wrong.

Ronny vdb
  • 2,324
  • 5
  • 32
  • 74

5 Answers5

3

Testing the code gives the following error:

Uncaught TypeError: function parse() { [native code] } is not a constructor

This is because of the "new" keyword. Removing this fixes your problem:

// Define the date I want to check
var targetDate = "2015-02-04T19:30:00Z";
// Parse the string into a date object
var target = Date.parse(targetDate);
// Compare the target date againt a new date object set to 18:00:00
if (target < new Date().setHours(18, 0, 0)) {
  console.log("BEFORE");
} else {
  console.log("AFTER");
}
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
1

when you try to parse the target data, you don't have to use the new keyword.

Here's an working JSFiddle;

The code:

 // Define the date I want to check
 var targetDate = "2015-02-04T13:30:00Z";
 // Parse the string into a date object
 var target = Date.parse(targetDate);
 // Compare the target date againt a new date object set to 18:00:00
 if (target < new Date().setHours(18, 0, 0)) {
     alert("BEFORE");
 } else {
     alert("AFTER");
 }
Mathlight
  • 6,436
  • 17
  • 62
  • 107
0

Try:

var targetDate = new Date("2015-02-04T13:30:00Z");
var numHours = targetDate.getHours();
if (numHours < 18) {
  console.log("BEFORE");
} else {
  console.log("AFTER");
}
David P
  • 2,027
  • 3
  • 15
  • 27
0

If you can count on the ISO format and don't want to convert it to local time

you can just look at the hours substring.

var targetDate = "2015-02-04T13:30:00Z";

var isbefore18=targetDate.substring(11,13)-18<0;

isbefore18 /*  value: (Boolean) true */
kennebec
  • 102,654
  • 32
  • 106
  • 127
0

David P has the correct answer. A Date() is composed of a date part, and a time part

new Date().setHours(18,0,0)

creates a Date at 18:00 today, which will always be greater than 17:30 February 4, 2015, unless you have a time machine.

targetDate.getHours()

Returns the hour value of the time part, which it sounds like you are looking for.

lyjackal
  • 3,984
  • 1
  • 12
  • 25