I have the time stored as a fraction (done so it can be displayed on a graph), e.g. 15.5 is 3.30pm and 23.25 is 11.15pm. I need to turn those numbers into strings in the format HH:MM:SS. Is there a simple way of doing this?
views:
61answers:
3The fraction also stores seconds as well as minutes, but that looks like what I need so far
Sarah
2010-07-26 11:43:59
@Sarah, added an additional way completely manual..
Gaby
2010-07-26 11:50:19
@Sarah, added version with seconds :)
Gaby
2010-07-26 12:00:02
+4
A:
var fraction = 23.5;
var date = new Date(2000, 1, 1); // use any date as base reference
date.setUTCSeconds(fraction * 3600); // add number of seconds in fractional hours
Then use a date formatting script such as this, or Date.js if you're not fond or formatting and padding.
date.format("HH:MM:ss"); // 23:30:00
See an example. I'm using the formatting function from here.
Anurag
2010-07-26 12:00:53
+1 yes, Steven Leviathin's date formatter is brilliant for flexible date formatting in JS: http://blog.stevenlevithan.com/archives/date-time-format
fearoffours
2010-07-26 12:28:00
@Gaby - I recently discovered that JavaScript set* functions handle overflow very nicely and put me in awe :) .. @fearoffours - It is indeed an awesome lightweight library for formatting dates when Date.js feels a little too much :)
Anurag
2010-07-26 12:31:34
A:
Manual function:
var time = function(num) {
if(num < 0 || num >= 24) {throw "Invalid number");}
var x = num > 13 ? num - 12 : num;
var h = Math.floor(x);
var min = x - h;
var ampm = num >= 12 && num < 24 ? "pm" : "am";
return (h + ":" + Math.floor(min * 60) + ampm);
};
Tests:
time(13.40); // 1:24pm
time(11.25); // 11:15pm
time(12.50); // 12:30pm
time(23.50); // 11:30pm
time(0.50); // 0:30am
time(24.00); // error!!
naikus
2010-07-26 12:25:54