开发者

Javascript: How to turn the time (stored as a fraction) into a readable string?

开发者 https://www.devze.com 2023-01-08 16:38 出处:网络
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 num开发者_如何学Pythonbers into strings in the format HH:M

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 num开发者_如何学Pythonbers into strings in the format HH:MM:SS. Is there a simple way of doing this?


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.


Something like this ?

var fraction = 14.5;
var hours = Math.floor(fraction); // extract the hours (in 24 hour format)
var mins = 60 * (fraction - hours); // calculate the minutes
t = new Date(); // create a date/time object

t.setHours(hours); // set the hours
t.setMinutes(mins); // set the mins
console.log(t.toTimeString()); //show it

or completely manual

var fraction = 14.5;
var hours = Math.floor(fraction);
var mins = 60 * (fraction - hours);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';

formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + mins).substr(-2) + ':00 ' + ampm;
console.log(formatted);

Update

And a version with seconds as well..

var fraction = 14.33;
var hours = Math.floor(fraction);
var allseconds = 3600 * (fraction - hours);
var minutes = Math.floor(allseconds / 60);
var seconds = Math.floor(allseconds % 60);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';

formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2) + ' ' + ampm;
console.log(formatted);


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!!
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号