简体   繁体   中英

javascript time 24 hour to 12 hour with a click button

I want to make a javascript code that will show time in 12 hour format (with AM/PM) by default. And there'll be a button below that, and when i click that button that'll change the time to 24 hour format (Military time). Again when I click that button, the time will be changed to previous 12 hour format. How can I do that.

Here is the link of my code- code

What i want to do here is- when i click that "ab" button it'll change the first time (12 hour) to 24 hour format. And again when I click that button the first time will be changed to the previous 12 hour format.

The javascript Date when initialized using something like var currentDate = new Date(); will hold the current date and time. You can then use the currentDate.getHours() method to get the hours in 24 hour format.

Changing this to 12 hour format first involves checking whether the hour is greater than or equal to 12 (in which case the suffix will be PM, otherwise it will be AM). After this you just modulo the hours by 12.

The minutes and seconds can be retrieved using currentDate.getMinutes() and currentDate.getSeconds() respectively.

Here is a fiddle that demonstrates the above.

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