1

I have a number which represent time and I need to convert this number into string.

Like n = 800 , it represent time = 8:00

Currently I am doing this:

n = 800;
string time = '' +  n/100 + ' : ' + n % 100  ;

but time become 8 : 0 but I want to minutes in two digit format like 8 : 00 Anybody please help me there?

1
  • So 8:15 am would be represented as "815"? Commented Sep 5, 2015 at 4:59

3 Answers 3

2
var n = 800;    
var hours = Math.floor(n/100);
var minutes = ('0' + (n%100)).slice(-2);
var time = hours + ':' + minutes;

Note the rounding on hours as well, otherwise you could end up with something like "8.56:56".

Sign up to request clarification or add additional context in comments.

Comments

1

If all you are trying to do here is insert a colon before the last two digits you can just do a string replace:

var time = ("" + n).replace(/(\d\d)$/,":$1");

Or slice out the hours and minutes and concatenate with a colon:

var time = "" + n;
time = time.slice(0,-2) + ":" + time.slice(-2);

Comments

0

Just a shortcut solution :P

var a = 800;
var b = a.toString();
var first = b.replace(b.substring(b.length - 2),":"+b.substring(b.length - 2));

http://jsfiddle.net/6pfhyhhg/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.