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

Fixed Remove class issue with MooTools

Posted on 7 years ago

Bhumi

Drupal Tutorial for Beginners

Posted on 6 years ago

Bhumi

How To Reset resourceID in MODx

Posted on 6 years ago

Bhumi

How to use ezSQL with example

Posted on 4 years ago

Bhumi

Constructor and Destructor in PHP

Posted on 7 years ago

Bhumi

Hello world

Updated 5 days ago

Nick Carter

In depth Understanding of Laravel Core

Updated 2 months ago

Bhumi

ECMAScript 6 New Features – 2

Updated 1 year ago

Bhumi

The Reader’s Poll – June 2015

Posted on 4 years ago

Bhumi

The Reader’s Poll – August 2014

Posted on 4 years ago

Bhumi

The Reader’s Poll – June 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – May 2014

Posted on 5 years ago

Bhumi

The Readers’ Poll – August 2013

Posted on 5 years ago

Bhumi