Back to Top

Convert 12-hour datetime to 24-hour datetime in JavaScript

Convert 12-hour datetime to 24-hour datetime in JavaScript

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:


function convertDateTo24Hour(date){
    var elem = date.split(' ');
    var stSplit = elem[1].split(":");// alert(stSplit);
    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;
    }

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

Table layout using DIV tags

Posted on 13 years ago

Bhumi

Control Flow Functions in MySQL

Posted on 10 years ago

Bhumi