admin管理员组

文章数量:1413422

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?

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?

Share Improve this question asked Jul 16, 2012 at 16:18 dotNetNewbiedotNetNewbie 7994 gold badges17 silver badges35 bronze badges 3
  • Works for me jsfiddle/vFnh7 – gen_Eric Commented Jul 16, 2012 at 16:20
  • simply use var hrs = parseInt('your hours string here'); – Roko C. Buljan Commented Jul 16, 2012 at 16:23
  • This doesn't actually result in valid 12 hr format – Esailija Commented Jul 16, 2012 at 16:23
Add a ment  | 

5 Answers 5

Reset to default 2

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./jsref/jsref_parseint.asp

You can convert it to an int:

var hrsInt = parseInt(hrs);

本文标签: javascriptConvert 24 hr format to 12 hr formatStack Overflow