0

i try to compare two timestamps like this:

var nowDate = new Date();
var givenDate = new Date(parseInt(year), parseInt(month), parseInt(day), parseInt(hour), parseInt(minute), 0);
var nd_timestamp = nowDate.getTime();
var gd_timestamp = givenDate.getTime();

if (nd_timestamp > gd_timestamp) {
    alert("yes");   
}

But it is not working properly. If i look at the nd_timestamp and gd_timestamp everything looks fine, but the if-clause is not working. If i remove the parseInt(year)... and enter Date(2012, 04, 20, 0, 0, 0) the if-clause is working.

The variables year, month etc. comes through a function, but if i debug it with alert(year) etc. everything is fine. The given date through the form is smaller than the actual date.

Does anybody know why it is not working with variables?

Thanks!

Torben
  • 5,388
  • 12
  • 46
  • 78
  • 1
    You know that JavaScript Date objects expect a month value from 0 to 11, and not 1 to 12, right? – Pointy Jun 30 '12 at 14:19
  • 1
    Also your parseint calls should look like `parseInt(month, 10)` - if you don't do that you'll get weird results from "08" and "09". – Pointy Jun 30 '12 at 14:20
  • Hello, thanks. I use now parseInt(var, 10) and for the month i do: parseInt(month-1,10). That seems to be correct. – Torben Jun 30 '12 at 14:26
  • It should be `parseInt(month, 10) - 1`, though if the month is really a valid number just `month - 1` should work - JavaScript will convert the string to a number because of the `-` operator so the call to `parseInt()` in that case is superfluous. Of course, you may want to check for validity on those field values. – Pointy Jun 30 '12 at 14:27
  • You don't need to use parseInt, strings are fine. And `month - 1` will return a Number provided month is string that converts to a number. e.g. given `y='2012', m='06', d='05'` then `new Date(y,--m,d)` will return the correct date. – RobG Jun 30 '12 at 14:28

2 Answers2

2

You should check the values you pass to the Date constructor for validity, which includes explicitly specifying 10 as the second parameter to all of your parseInt calls to avoid nasty surprises.

Regarding the second parameter, the documentation says

While this parameter is optional, always specify it to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

Jon
  • 428,835
  • 81
  • 738
  • 806
2

You have to take 1 from Month because for some reason it is zero based, unlike the others.

SpacedMonkey
  • 2,725
  • 1
  • 16
  • 17
  • Those zero-indexed months are so evil, here is the why: http://stackoverflow.com/questions/2552483/why-does-the-month-argument-range-from-0-to-11-in-javascripts-date-constructor – Christophe Roussy Jun 06 '16 at 14:12