title: How to the get the beginning of day of a date in javascript -- factoring in timezone
body: <p>I am struggling to find out the beginning of day factoring in timezones in javascript.  Consider the following:</p>
  
  <pre><code>   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())
  </code></pre>
  
  <p>I expect when i pass a Pacific Timezone offset, to get: <code>2011-12-08 08:00:00 UTC</code> and so on.</p>
  
  <p>What is the correct way to achieve this?</p>
  
  <p>I think that part of the issue is that <a href="http://www.w3schools.com/jsref/jsref_sethours.asp" rel="nofollow">setHours</a> method sets the hour (from 0 to 23), according to local time.</p>
  
  <p>Also note that I am using javascript embedded in mongo, so I am unable to use any additional libraries.</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p>Jeez, so this was really hard for me, but here is the final solution that I came up with the following solution.  The trick was I need to use setHours or SetUTCHours to get the beginning of a day -- the only choices I have are system time and UTC.  So I get the beginning of a UTC day, then add back the offset!</p>
  
  <pre><code>// Goal is given a time and a timezone, find the beginning of day
  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;
  }
  </code></pre>