Mike Burnwood
Mike Burnwood

Reputation: 279

JavaScript - Converting time from 12h into 24h format

I tried many methods, but I always end up without solution. What I need is a javascript code which can convert time from div.postedOn from 12h to 24h format.

div.postedTime example:

<div class="postedOn"><img src="http://assets7.thatsite.com/images/forums/post/reply.gif?v3" alt="">&nbsp;&nbsp;Posted on June 3, 2012 1:46 AM</div>

So, I need to convert '1:46 PM' to '01:46' without removing any contents from the <div>.

Upvotes: 1

Views: 1481

Answers (4)

Mark Kimitch
Mark Kimitch

Reputation: 332

var str = "12:00 AM";
var regex = /([01]?\d)(:\d{2}) (a.m.|p.m.|AM|PM)/g;
var match = regex.exec(str);
var test;
if (match[1] == 12 && (match[3] == 'p.m.' || match[3] == 'PM')) {
    test = '12 h';
} else if (match[1] == 12 && (match[3] == 'a.m.' || match[3] == 'AM')) {
    test = '0 h';
} else {
    test = str.replace(regex, (+match[1] + (match[3]=='a.m.'? 0 : 12)) + ' h');
}
console.log(test);

Would this work, in regards to catching those pesky "12 AM" and "12 PM" situations?

Upvotes: 0

Art
Art

Reputation: 5924

Similar to Kolink, adding another regex solution...

var str = "Posted on June 3, 2012 2:00 PM";
var regex = /([01]?\d)(:\d{2}) (AM|PM)/g;
var match = regex.exec(str);
str.replace(regex, (+match[1] + (match[3]=='AM'? 0 : 12)) + match[2] + match[3]);

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

If the format is always the same, then this will work fine:

out = in.replace(/(\d+):(\d+) ([AP])M/,function(m) {
    m[1] = m[1]%12;
    if( m[3] == "P") m[1] += 12;
    if( m[1] < 10) m[1] = "0"+m[1];
    return m[1]+":"+m[2];
});

Upvotes: 4

Shaun Wild
Shaun Wild

Reputation: 1243

I'm not 100% sure because i've not done javascript in a while, but you would do something like this.. (this is pseuedo btw)

if( timeString.contains("pm") ) {
hour += 12%24;
}

I'm not 100% sure if that will work, but that is the basic idea none the less. i hope i helped.

Upvotes: 0

Related Questions