1

How can I determine if hours and minutes were specified or not in a JavaScript Date instance?

Date object without hours:minutes:

var date = new Date('2013-03-15');
date.getHours();
> 1
date.getMinutes();
> 0

When I specify what seems to be the default hours:minutes (01:00), the return appears to be identical.

var date2 = new Date('2013-03-15 01:00');
date2.getHours();
> 1
date2.getMinutes();
> 0
Frode
  • 501
  • 2
  • 7
  • 20
  • 1
    You can't, only work around that by wrapping it in a custom class that can keep track of that information. – mhitza Mar 15 '13 at 10:31

1 Answers1

0

That +1 is because of your local timezone offset being applied. Oslo is Central European Time so +1 from UTC.

.getHours() Returns the hour (0-23) in the specified date according to local time - see MDN Date documentation.

You can use .getUTCHours() to return the non-localised hours instead.

Alternatively, you could us .getTime() which returns milliseconds and is not affected by timezone, then divide by 86400000 (milliseconds in a day) and if you get an integer then the hours, minutes, seconds were all 0.

For example:

d = new Date(2013, 2, 15)
if (d.getTime() / 86400000 % 1 === 0) // date is midnight

Note: borrowed "is integer" trick from How do I check that a number is float or integer?

Community
  • 1
  • 1
andyb
  • 43,435
  • 12
  • 121
  • 150