Skip to content

Instantly share code, notes, and snippets.

@z-------------
Last active August 29, 2015 14:19
Show Gist options
  • Save z-------------/6b5ebf8b5b9a62917dc5 to your computer and use it in GitHub Desktop.
Save z-------------/6b5ebf8b5b9a62917dc5 to your computer and use it in GitHub Desktop.
A couple of simple time related methods in JavaScript
var time = {};
time.parse = function(str){
// time since start of day. accepts 24 hour time in 23:59 format
var strSplit = str.split(":");
var hrInt = strSplit[0];
var minInt = strSplit[1];
var msInt = hrInt * 60 * 60 * 1000 + minInt * 60 * 1000;
return msInt;
};
time.sinceZero = function(){
// returns number in milliseconds since start of day
var now = new Date();
return (
now.getHours() * 60 * 60 * 1000
+ now.getMinutes() * 60 * 1000
+ now.getSeconds() * 1000
+ now.getMilliseconds()
);
};
time.stringify = function(ms){
// returns 24 hour formatted time string
// ms is time since start of day
var dec = ms / 1000 / 60 / 60;
var hr = Math.floor(dec);
var minDec = dec - hr;
var min = 60 * minDec;
return [hr, zpad(min, 2)].join(":");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment