0

I have a GMT time format and I changed it to my local browser time by using:

var newDate = new Date(GMTFromat);
mytime= newDate.toLocaleString();

The output is:

3/12/2010 1:02:00 PM

Now I want to change 12 hours to 24 hours format in javascript.
Example:

3/12/2010 13:02:00 

Any suggestion?

Thanks

Spidy
  • 1,137
  • 3
  • 28
  • 48
user3409650
  • 505
  • 3
  • 12
  • 25

3 Answers3

0

enter code hereIts a copy of SO link

Code from the above link:

function to24Hour(str) {

  var tokens = /([10]?\d):([0-5]\d):([0-5]\d) ([ap]m)/i.exec(str);

  if (tokens == null) { return null; }
    if (tokens[4].toLowerCase() === 'pm' && tokens[1] !== '12') {
      tokens[1] = '' + (12 + (+tokens[1]));
    } else if (tokens[4].toLowerCase() === 'am' && tokens[1] === '12') {
      tokens[1] = '00';
    }
  return tokens[1] + ':' + tokens[2] + ":" + tokens[3]; 
}

Edit:

var date = "3/12/2010 8:45:59 AM";
var dateTime = date.split(" ");
var datePart = dateTime[0];
var timePart = dateTime[1] + " " + dateTime[2];
timePart = to24Hour(timePart);

var finalDate = datePart + timePart;
Community
  • 1
  • 1
Arjit
  • 3,290
  • 1
  • 17
  • 18
  • thanks man! and if I want to keep the date too, what should I do? because it just returns the time. but I need both date and time together – user3409650 Mar 12 '14 at 12:34
  • you can separate the date part & time part from your input, then can pass the time part to this method , then append the result of this method with your date part – Arjit Mar 12 '14 at 12:39
0

This can be done in any number of ways, but I wanted to do it using just the replace method. Here you go:

(new Date()).toLocaleString().replace(/(.+ )(\d+)(:.+)(\wM)/g, function replacer(match, p1, p2, p3, p4) {
    return p1 + (p4 === "PM" ? (12 + Number(p2)) : p2) + p3;
});

DEMO

tewathia
  • 6,890
  • 3
  • 22
  • 27
-1
$(function(){
    alert(
        moment("3/12/2010 1:02:00 PM", "M/DD/YYYY hh:mm:ss A").
            format("M/DD/YYYY HH:mm:ss")
    );
});

fiddle

Here small hh for 12-clock system and HH for 24 clock system.

setec
  • 15,506
  • 3
  • 36
  • 51