Here I am going to share one function I have used to change the date from 12 hours to 24 hours.Recently I want to store date into the database and to store date into the database, you need to have a particular format, you can’t save as 12 hours AM or PM.
So, I have displayed a date as 12 hours with AM or PM and then apply following function which convert 12 hours date into 24 hours.
Let’s understand the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function convertDateTo24Hour(date){ var elem = date.split(' '); var stHour = stSplit[0]; var stMin = stSplit[1]; var stAmPm = elem[2]; var newhr = 0; var ampm = ''; var newtime = ''; //alert("hour:"+stHour+"\nmin:"+stMin+"\nampm:"+stAmPm); //see current values if (stAmPm=='PM') { if (stHour!=12) { stHour=stHour*1+12; } }else if(stAmPm=='AM' && stHour=='12'){ stHour = stHour -12; }else{ stHour=stHour; <strong> } </strong> return elem[0]+" "+stHour+':'+stMin; } |
That’s it. You can alert your date and check you get the right format of the date.
Also Read:
JavaScript Ticker for Database Values
To convert PHP array into Javascript array
Convert date from one format to another format using javascript
As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.