Skip to content

Instantly share code, notes, and snippets.

@KLicheR
Last active December 17, 2015 10:28
Show Gist options
  • Save KLicheR/5594689 to your computer and use it in GitHub Desktop.
Save KLicheR/5594689 to your computer and use it in GitHub Desktop.
Get time components.
/**
* Get time components of milliseconds.
*/
var totalTime = function(milliseconds) {
var aSecond = 1000;
var aMinute = 60*aSecond;
var anHour = 60*aMinute;
var aDay = 24*anHour;
var aWeek = 7*aDay;
var aYear = 365.25*aDay;
var mathFn = (milliseconds<0?'ceil':'floor');
this.years = function() { return Math[mathFn](milliseconds / aYear); };
this.days = function() { return Math[mathFn]((milliseconds % aYear) / aDay); };
this.hours = function() { return Math[mathFn](((milliseconds % aYear) % aDay) / anHour); };
this.minutes = function() { return Math[mathFn]((((milliseconds % aYear) % aDay) % anHour) / aMinute); };
this.seconds = function() { return Math[mathFn](((((milliseconds % aYear) % aDay) % anHour) % aMinute) / aSecond); };
this.milliseconds = function() { return Math[mathFn](((((milliseconds % aYear) % aDay) % anHour) % aMinute) % aSecond); };
this.totalWeeks = function() { return Math[mathFn](milliseconds / aWeek); };
this.totalDays = function() { return Math[mathFn](milliseconds / aDay); };
this.totalHours = function() { return Math[mathFn](milliseconds / anHour); };
this.totalMinutes = function() { return Math[mathFn](milliseconds / aMinute); };
this.totalSeconds = function() { return Math[mathFn](milliseconds / aSecond); };
}
/**
* Get the number of milliseconds since Sunday at 00:00:00 [UTC].
*/
Date.prototype.toUTCWeekMilliseconds = function() {
return (this.getUTCDay()*24*60*60*1000) // Days
+ (this.getUTCHours()*60*60*1000) // Hours
+ (this.getUTCMinutes()*60*1000) // Minutes
+ (this.getUTCSeconds()*1000) // Seconds
+ this.getUTCMilliseconds(); // Milliseconds
}
@KLicheR
Copy link
Author

KLicheR commented Apr 24, 2015

Instead of the totalTime class, you can also use the Moment.js library which can handle durations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment