Mark Vincent Manjac
Mark Vincent Manjac

Reputation: 505

jQuery: How to get the difference between time with 12hr format and time with 24hr format

I'm new in jQuery and I really don't know have any idea how to get this. I want to get the 12hr format result of the difference between time with 12hr format and time with 24hr format. Example: given the time "1:30:25 AM" and subtract it to "00:32:20", then the result should be "12:58:05 AM". Please help me to get this.

Upvotes: 0

Views: 756

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58860

Result in 24-hr format

var dt = '1/1/2000 ';
var date = new Date(new Date(dt + '1:30:25 AM') - new Date(dt + '00:32:20'));
alert("24-hr format: " + date.toISOString().substr(11, 8));

Result: 00:58:05

Result in 12-hr format

function timeFormat12Hr(date) {
    var hours = date.getUTCHours();
    var minutes = date.getUTCMinutes();
    var seconds = date.getUTCSeconds();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
    return strTime;
}

var dt = '1/1/2000 ';
var date = new Date(new Date(dt + '1:30:25 AM') - new Date(dt + '00:32:20'));
alert("12-hr format: " + timeFormat12Hr(date));

Result: 12:58:05 AM

NOTE: I'm using string '1/1/2000 ' to construct a Date object, but it could be any date because we're only interested in time portion of it.

See this JSFiddle for demonstration.

Upvotes: 1

Sharn White
Sharn White

Reputation: 624

Some simple javascript should do the job. Once you have a date object you can output it in whatever format you want.

var year = 2015; var month = 5, var day = 18, var hours = 1; minutes = 30; seconds = 25;
var date = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var new_format = (date->getHours()+1)+'-'+date->getMinutes();

date returns 0-23 so you have to add +1 (this is why i tend to favor moment.js, as mentioned below)

http://www.w3schools.com/jsref/jsref_obj_date.asp (for other methods of creating date object)

Otherwise maybe give moment.js a try, it's awesome for date/time calculations.

http://momentjs.com/

Upvotes: 0

Related Questions