i have a string of like 120 i want to convert into time like 02:00(hh:mm).
Actual :
120
Expected:
02:00.
so, please suggest result.
i have a string of like 120 i want to convert into time like 02:00(hh:mm).
Actual :
120
Expected:
02:00.
so, please suggest result.
Fiddle: http://jsfiddle.net/ow418gLc/1/
var value = 120
var hours = pad(Math.floor(value / 60));
var minutes = pad(value % 60);
function pad(n){
n = n.toString();
n = n.length < 0 ? n: ("0" + n);
return n;
};
console.log(hours + ":" + minutes);
output:
02:00
EDIT: There is a small bug in the padding above and I converted this to a real function.
function convertMinutesToTime(minutes) {
function pad(n) {
n = n.toString();
n = n.length < 2 ? ("0" + n) : n;
return n;
};
var paddedHours = pad(Math.floor(minutes / 60));
var paddedMinutes = pad(minutes % 60);
return paddedHours + ":" + paddedMinutes
}
console.log(convertMinutesToTime(120));
You'd probably need to do three steps:
Turn a string into a number:
var number = parseInt(string, 10);
Create a Date from a number of seconds:
var date = new Date(2000, 0, 1, 0, 0, seconds);
Create a formatted date string from a Date. For that, you might like to use moment.js and do:
var formatted = moment(date).format('hh:ss');