views:

25

answers:

2

Hi everybody , I have a question, how can I change time from 24hr format to 12, the easiest way, in javascript or Jquery .

This is what I have :

TempDate = $.datepicker.formatDate('MM dd, yy', TempDate);
var ChangeDate = TempDate + " " + TradeTime;    

now TradeTime= 15:59 , but I wanna be 3:59PM

What is the easiest way , or can I use datapicker or to force this format in the same time with date.

Thanks

A: 

This helped me :

         TradeTime = ("" + TradeTime).split(":",2);


        if (TradeTime[0] < 12)
           {
           a_p = "AM";
           }
        else
           {
           a_p = "PM";
           }
        if (TradeTime[0] == 0)
           {
           TradeTime[0] = 12;
           }
        if (TradeTime[0] > 12)
           {
           TradeTime[0] = TradeTime[0] - 12;
           }
Alexander Corotchi
A: 

I'm afraid you will just have to do it manually, quick n dirty, for now ;)

     function to12Hrs(strHrs, strMin) {            
        var hrs = Number(strHrs);
        var min = Number(strMin);
        var ampm = "am";

        if(isNaN(hrs) || isNaN(min) || hrs > 23 || hrs < 0)   {
           throw ("Invalid Date " + str24Hrs);
        }           

        if(hrs >= 12)   {
           hrs = (hrs - 12) || 12;
           ampm = "pm";
        }
        var strHr = (hrs < 10) ? "0".concat(hrs) : hrs;
        var strMin = (min < 10) ? "0".concat(min) : min;
        return (strHr + ":" + strMin + ampm);
     }

     var arr = "12:30".split(":");
     alert(to12Hrs(arr[0], arr[1])); // 12:30pm

     arr = "11:00".split(":");            
     alert(to12Hrs(arr[0], arr[1])); // 11:00am

     arr = "02:00".split(":");
     alert(to12Hrs(arr[0], arr[1])); // 02:00am

     arr = "20:00".split(":");
     alert(to12Hrs(arr[0], arr[1])); // 08:00pm
naikus