Search code examples
javascriptdatetimetimeformatting

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript


What is the best way to convert the following JSON returned value from a 24-hour format to 12-hour format w/ AM & PM? The date should stay the same - the time is the only thing that needs formatting.

February 04, 2011 19:00:00

P.S. Using jQuery if that makes it any easier! Would also prefer a simple function/code and not use Date.js.


Solution

  • UPDATE 2: without seconds option

    UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/

    I created this function to do this:

    function formatDate(date) {
      var d = new Date(date);
      var hh = d.getHours();
      var m = d.getMinutes();
      var s = d.getSeconds();
      var dd = "AM";
      var h = hh;
      if (h >= 12) {
        h = hh - 12;
        dd = "PM";
      }
      if (h == 0) {
        h = 12;
      }
      m = m < 10 ? "0" + m : m;
    
      s = s < 10 ? "0" + s : s;
    
      /* if you want 2 digit hours:
      h = h<10?"0"+h:h; */
    
      var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);
    
      var replacement = h + ":" + m;
      /* if you want to add seconds
      replacement += ":"+s;  */
      replacement += " " + dd;
    
      return date.replace(pattern, replacement);
    }
    
    alert(formatDate("February 04, 2011 12:00:00"));