Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time conversion from 24hrs to 12hrs

I am getting the time like 13.40, but i need to convert it to 1.40.. any one know, what is the best way to do this. i am using jquery to make time.

my code is :

var time = new Date(myDate);
var hours = time.getHours();

alert(hours);
like image 362
3gwebtrain Avatar asked May 25 '11 11:05

3gwebtrain


People also ask

How is 2213 hours converted to 12-hour?

2213 Hours Is 10:13 PM in Regular Time - Capitalize My Title.


2 Answers

if (hours > 12) {
  hours -= 12;
}

Um, as simple as that.

like image 142
maple_shaft Avatar answered Oct 23 '22 19:10

maple_shaft


Use the modulus operator, % for this

var input = "13.40"; 
var atoms = input.split(".");
var output = atoms[0] % 12 + "." + atoms[1];
output; // "1.40";

If you want to prefix with 0 then you can do this

var output = ("0" + atoms[0] % 12).slice(-2) + "." + atoms[1];
output; // "01.40";

If you want AM/PM as a suffix

var output = ("0" + atoms[0] % 12).slice(-2) + "." + atoms[1] + 
     (atoms[0] < 13 ? " AM" : " PM");
output; // "01.40 PM";
like image 40
Sean Kinsey Avatar answered Oct 23 '22 21:10

Sean Kinsey