Skip to content

Instantly share code, notes, and snippets.

@brapse
Created May 15, 2012 15:49
Show Gist options
  • Select an option

  • Save brapse/2702803 to your computer and use it in GitHub Desktop.

Select an option

Save brapse/2702803 to your computer and use it in GitHub Desktop.
var offsets = {
'year': 0,
'month': 1,
'day': 2,
'hour': 3,
'minutes': 4
};
var dateTrunc = function (pred, date) {
var trunc = offsets[pred];
var t = Date.UTC(date.getUTCFullYear(), // 01 dev 2012 00:00:00 GMT
trunc >= offsets.month ? date.getUTCMonth() : 0, // 01 Apr 2012 00:00:00 GMT
trunc >= offsets.day ? date.getUTCDate() : 1, // 04 Apr 2012 00:00:00 GMT
trunc >= offsets.hour ? date.getUTCHours() : 0, // 04 Apr 2012 01:00:00 GMT
trunc >= offsets.minute ? date.getUTCMinutes() : 0, // 04 Apr 2012 01:59:00 GMT
0, //seconds
0); //microsecond
return new(Date)(t).toISOString();
};
var date = new Date;
console.log('base', date);
console.log('year', dateTrunc('year', date));
console.log('month', dateTrunc('month', date));
console.log('day', dateTrunc('day', date));
console.log('hour', dateTrunc('hour', date));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment