datetime - JavaScript set date to beginning of x -


im working on fn set date beginning of minute/hour/day/week/month/quarter/year.

i've got start week doing like:

var date = new date(),     day = d.getday(),     // adjust when day sunday     diff = d.getdate() - day + (day == 0 ? -6 : 1);      var updateddate = new date(date.setdate(diff); 

but have wonder if there better way ( or framework ) accomplish type of thing?

this best i've been able come far:

function beginningof(period, date) {     date = new date(date.valueof()); // copy date      if (period === "year" || period == "quarter") {         date.setmonth(period === "quarter"                       ? 3 * math.floor(date.getmonth() / 3)                       : 0);         period = "month"; // round down start of month     }      if (period === "month" || period === "week") {         date.setdate(period === "week"                      ? date.getdate() - date.getday() // sunday first day, adjust suit                      : 1);         period = "day"; // round dow start of day     }      // intentional switch fall-through     switch (period) {         case "day":             date.sethours(0);         case "hour":             date.setminutes(0);         case "minute":             date.setseconds(0);             date.setmilliseconds(0);     }      return date; } 

see http://jsfiddle.net/alnitak/6hj9u/

it's harder problem had expected...


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -