javascriptjquerydatedatetime

Get Meridian from time in Javascript


I have following time "Mon Jun 22 03:45:24 PDT 2015" how can I get Meridian using Javascript. I was doing this:

d= Mon Jun 22 03:45:24 PDT 2015;
var hours = d.getHours();
var meridiem = "AM";

if (d.getHours() > 12) {
   hours = d.getHours() % 12;
   if (hours == 2) {
      hours = 12;
   }
   meridiem = "PM";
}

But its not working in IE 8.


Solution

  • you define

    d= Mon Jun 22 03:45:24 PDT 2015;
    

    actually it is nothing in javascript some browser more intelligent some not, it's up to the browser behaviour you have to tell javascript like that

    function getCurrentTime() {
      var currentTime;
      // here we can give our date
      var currentDate = new Date("Mon Jun 22 03:45:24 PDT 2015");
      // OR we can define like that also for current date
      // var currentDate = new Date();
      var hour = currentDate.getHours();
      var meridiem = hour >= 12 ? "PM" : "AM";
      currentTime = ((hour + 11) % 12 + 1) + ":" + currentDate.getMinutes() + meridiem;
      return currentTime;
    }
    
    console.log(getCurrentTime());