I'm having trouble determining the start of a day while factoring in timezones using javascript. Consider this example:
var raw_time = new Date(this.created_at);
var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms);
// This resets timezone to server timezone
var offset_day = new Date(offset_time.setHours(0,0,0,0))
// always returns 2011-12-08 05:00:00 UTC, no matter what the offset was!
// This has the same issue:
var another_approach_offset_day = new Date(offset_time.getFullYear(),offset_time.getMonth(),offset_time.getHours())
When I provide a Pacific Timezone offset, I expect to receive: 2011-12-08 08:00:00 UTC
and so forth.
What is the correct way to achieve this?
I believe part of the problem lies in the fact that the setHours method sets the hour (from 0 to 23) based on local time.
Please note that I am utilizing javascript embedded in mongo, restricting me from employing any additional libraries.
Thank you!
Wow, this was quite a challenge for me, but I managed to come up with a final solution. The key was realizing I needed to use setHours or SetUTCHours to find the start of a day - my only options being system time and UTC. So, I obtain the beginning of a UTC day and then adjust for the offset!
// Objective: determine the start of a day given a time and timezone
function(timestamp, selected_timezone_offset) {
var raw_time = new Date(timestamp)
var offset_time = new Date(raw_time.getTime() + selected_timezone_offset);
offset_time.setUTCHours(0,0,0,0);
var beginning_of_day = new Date(offset_time.getTime() - selected_timezone_offset);
return beginning_of_day;
}