tuscan88
tuscan88

Reputation: 5829

why is javascript date an hour behind?

Hi I am trying to create a unix timestamp to represent the latest time of the current day (23:59:59) like so:

current_date = new Date();
end = new Date(current_date.getFullYear(), current_date.getMonth(), current_date.getDate(),23,59,59);
end = end.getTime() / 1000;

When I alert out the unix timestamp and convert it back into a datetime though it is an hour behind and represents 22:59:59 rather than 23:59:59.

I have to pass 24 to the date function for the hour parameter instead of 23 if I want 11pm is this right?

I am located in England so my time should be in GMT

Upvotes: 4

Views: 1595

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

new Date() will create the date in your timezone, whereas timestamps are in UTC. You appear to be in BST (GMT+1) hence the off-by-one error.

Instead, create a date and then use setUTCHours(23), setUTCMinutes(59) and setUTCSeconds(59) to get the correct timestamp.

Upvotes: 5

Related Questions