简体   繁体   中英

Convert 24 hr format to 12 hr format

This might be really easy but I can't figure it out. I am trying to convert the 24 hr time to a 12 hr time to display on the UI.

var hrs = '<%=Model.Scheduled.Value.Hour%>';
var hrs12 = hrs > 12 ? hrs - 12 : hrs;
$("#ScheduledHour").val(hrs12);

But the above is not working coz hrs is a string. Any suggestions on how to get this working?

you can use parseInt() :

var hrs = '<%=Model.Scheduled.Value.Hour%>';
hrs = parseInt(hrs, 10) // converts the value to an integer
var hrs12 = hrs > 12 ? hrs - 12 : hrs;
$("#ScheduledHour").val(hrs12);
var hrs = '<%=Model.Scheduled.Value.Hour%>'
    thrs = parseInt(hrs, 10);  // As hrs is string, so you need to convert it to
                               // integer using parseInt(str, radix), don't forget to use 
                               // radix parameter

var hrs12 = thrs > 12 ? thrs - 12 : thrs;
$("#ScheduledHour").val(hrs12);

Just convert hrs to a number:

hrs = '<%=Model.Scheduled.Value.Hour%>' * 1;

Also, your question is misleading. Really all you're asking is "How do I convert a string to a number in JavaScript?" In which case, Google probably could have helped you out.

You need to convert your hrs variable to a number. There are a number of ways to do this, but parseInt is probably your best bet here...

parseInt: http://www.w3schools.com/jsref/jsref_parseint.asp

您可以将其转换为int:

var hrsInt = parseInt(hrs);
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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM