Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

JavascriptTime Format

Javascript Problem Overview


The server is sending a string in this format: 18:00:00. This is a time-of-day value independent of any date. How to convert it to 6:00PM in Javascript? I could prepend today's date as a string to the value sent by the server and then parse the combined values and then try the .toTimeString() method of the Date object, but the format that time method emits is 24-hour time with a seconds chunk. I could write a function, but is there something built in?

Javascript Solutions


Solution 1 - Javascript

Nothing built in, my solution would be as follows :

function tConvert (time) {
  // Check correct time format and split into components
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
  
  if (time.length > 1) { // If time format correct
    time = time.slice (1);  // Remove full string match value
    time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
    time[0] = +time[0] % 12 || 12; // Adjust hours
  }
  return time.join (''); // return adjusted time or original string
}

tConvert ('18:00:00');

This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.

The return value is the adjusted time if a valid time was presented or the original string.

Working example

(function() {

  function tConvert(time) {
    // Check correct time format and split into components
    time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

    if (time.length > 1) { // If time format correct
      time = time.slice(1); // Remove full string match value
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
      time[0] = +time[0] % 12 || 12; // Adjust hours
    }
    return time.join(''); // return adjusted time or original string
  }

  var tel = document.getElementById('tests');

  tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {
    return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;
  }).join('\n');
})();

<h3>tConvert tests : </h3>
<pre id="tests">
  18:00:00
  18:00
  00:00
  11:59:01
  12:00:00
  13:01:57
  24:00
  sdfsdf
  12:61:54
</pre>

Solution 2 - Javascript

toLocaleTimeString() makes this very simple. There is no need to do this yourself anymore. You'll be happier and live longer if you don't try to attack dates with string methods. (They will fight back.)

const timeString = '18:00:00'
// Prepend any date. Use your birthday.
const timeString12hr = new Date('1970-01-01T' + timeString + 'Z')
  .toLocaleTimeString('en-US',
    {timeZone:'UTC',hour12:true,hour:'numeric',minute:'numeric'}
  );
document.getElementById('myTime').innerText = timeString12hr

<h1 id='myTime'></h1>

Solution 3 - Javascript

To get AM/PM, Check if the hour portion is less than 12, then it is AM, else PM.

To get the hour, do (hour % 12) || 12.

This should do it:

var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;

http://jsfiddle.net/Skwt7/4/

That assumes that AM times are formatted as, eg, 08:00:00. If they are formatted without the leading zero, you would have to test the position of the first colon:

var hourEnd = timeString.indexOf(":");
var H = +timeString.substr(0, hourEnd);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(hourEnd, 3) + ampm;

http://jsfiddle.net/Skwt7/3/

Solution 4 - Javascript

Based on gilly3's answer.

If you want to convert:

 08:00 to 08:00 AM 
 16:00 to 04:00 PM

Then this will work:

function tConv24(time24) {
  var ts = time24;
  var H = +ts.substr(0, 2);
  var h = (H % 12) || 12;
  h = (h < 10)?("0"+h):h;  // leading 0 at the left for 1 digit hours
  var ampm = H < 12 ? " AM" : " PM";
  ts = h + ts.substr(2, 3) + ampm;
  return ts;
};

https://jsfiddle.net/fpjs9g0L/

Solution 5 - Javascript

Short ES6 code

const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}
const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}

Solution 6 - Javascript

It will be better to use momentjs

Just a little conversation "2 PM" to "14.00"

const number = moment("02:00 PM", ["h:mm A"]).format("HH:mm");
cosole.log(number); 

// "14.00" "14.00" to "2 PM"

const number = moment("14.00", ["HH.mm"]).format("hh:mm a");
cosole.log(number); // "02:00 pm"

Solution 7 - Javascript

Researching this same question I have come across several complicated, hard to understand solutions, and then it dawned on me: There is a very simple solution that doesn't rely on hard-to-read regular expressions or other complicated code. Unless I am missing something obvious, this is an extremely simple, easy to understand solution:

function timeTo12HrFormat(time)
{   // Take a time in 24 hour format and format it in 12 hour format
    var time_part_array = time.split(":");
    var ampm = 'AM';
    
    if (time_part_array[0] >= 12) {
        ampm = 'PM';
    }
    
    if (time_part_array[0] > 12) {
        time_part_array[0] = time_part_array[0] - 12;
    }
    
    formatted_time = time_part_array[0] + ':' + time_part_array[1] + ':' + time_part_array[2] + ' ' + ampm;
    
    return formatted_time;
}



var time = timeTo12HrFormat(18:00:00);
console.log(time);  // 6:00:00 PM

Solution 8 - Javascript

A simple code for this will be

time = time.split(':');// here the time is like "16:14"
let meridiemTime = time[0] >= 12 && (time[0]-12 || 12) + ':' + time[1] + ' PM' || (Number(time[0]) || 12) + ':' + time[1] + ' AM';

You can adjust according to your time format

Solution 9 - Javascript

By Using Moment library we can convert 24 hour time format to 12 hour format.

moment('20:00', 'hh:mm').format('hh:mm')

//// output: 08:00

if you want to convert into AM and PM

moment('20:00', 'hh:mm a').format('hh:mm a')

//// output: 08:00 pm

Solution 10 - Javascript

Here's my way using if statements.

const converTime = (time) => {
  let hour = (time.split(':'))[0]
  let min = (time.split(':'))[1]
  let part = hour > 12 ? 'pm' : 'am';
  
  min = (min+'').length == 1 ? `0${min}` : min;
  hour = hour > 12 ? hour - 12 : hour;
  hour = (hour+'').length == 1 ? `0${hour}` : hour;

  return (`${hour}:${min} ${part}`)
}

console.log(converTime('18:00:00'))
console.log(converTime('6:5:00'))

Solution 11 - Javascript

function timeConversion(s) {
  if (s.trim().endsWith("PM")) {
    return s
      .replace(/\d{2}/, (_) => {
        return Number(_) === 12 ? 12 : Number(_) + 12;
      })
      .replace("PM", "");
  } else {
    if (s.trim().startsWith("12")) {
      return s.replace("12", "00").replace("AM", "");
    } else {
      return s.replace("AM", "");
    }
  }
}

Solution 12 - Javascript

Assuming you will get the date string in a proper format, I have a solution.

function parseDateTime(dt) {
        var date = false;
        if (dt) {
            var c_date = new Date(dt);
            var hrs = c_date.getHours();
            var min = c_date.getMinutes();
            if (isNaN(hrs) || isNaN(min) || c_date === "Invalid Date") {
                return null;
            }
            var type = (hrs <= 12) ? " AM" : " PM";
            date = ((+hrs % 12) || hrs) + ":" + min + type;
        }
        return date;
    }

    parseDateTime("2016-11-21 12:39:08");//"12:39 AM"
    parseDateTime("2017-11-21 23:39:08");//"11:39 PM"
    

Solution 13 - Javascript

Make sure that your time is in this format HH:MM:SS(PM/AM)

function timeConversion(s) {
    
    s = s.split(':');
    var time = s[2];
    if(time.charAt(2) === 'A' && parseInt(s[0]) == 12) s[0] = '00';
    if(time.charAt(2) === 'P' && parseInt(s[0]) <12) s[0] = parseInt(s[0])+12;
    if(s[0] >=24) s[0]-=24;
    var x = time.split('').slice(0,2);
    s[2] = x.join('');
    console.log(s.join(':'));
}

Solution 14 - Javascript

Here's a few variations that will work.

const oneLiner = (hour = "00", min = "00", sec = "00") => `${(hour % 12) || 12}:${("0" + min).slice(-2)}:${sec} ${(hour < 12) ? 'am' : 'pm'}`
console.log('oneliner', oneLiner(..."13:05:12".split(":")))



const oneLinerWithObjectInput = ({hour = "00", min = "00", sec = "00"} = {}) => `${(hour % 12) || 12}:${("0" + min).slice(-2)}:${sec} ${(hour < 12) ? 'am' : 'pm'}`
console.log('onelinerWithObjectInput', oneLinerWithObjectInput({
   hour: "13:05:12".split(":")[0],
   min: "13:05:12".split(":")[1],
   sec: "13:05:12".split(":")[2]
}))


const multiLineWithObjectInput = ({hour = "00", min = "00", sec = "00"} = {}) => {
   const newHour = (hour % 12) || 12
       , newMin  = ("0" + min).slice(-2)
       , ampm    = (hour < 12) ? 'am' : 'pm'
   return `${newHour}:${newMin}:${sec} ${ampm}`
}
console.log('multiLineWithObjectInput', multiLineWithObjectInput({
   hour: "13:05:12".split(":")[0],
   min: "13:05:12".split(":")[1],
   sec: "13:05:12".split(":")[2]
}))

Solution 15 - Javascript

This might help to format if you are using ES6.
Below code snippet will ignore the seconds. If you want to consider seconds you can add that as the first parameter.

   const formatFrom24Hrsto12Hrs = (time, ignoreZero = true) => {
      let [hours, minutes] = time.split(':')
      let modifier = +hours < 12 ? 'am' : 'pm'
      hours = +hours % 12 || 12
      minutes = ignoreZero && +minutes === 0 ? '' : `:${minutes}`
      return hours + minutes + modifier
    }

Solution 16 - Javascript

Thanks to @HBP for paving the way here!

I found this to add a little flexibility to the solution.

The RegEx has been updated to accommodate times before noon.

This solution allows you to pass any string to it. As long as a valid time (in this format 18:00 || 18:00:00 || 3:00 || 3:00:00) is somewhere in that string, you're good to go.

Note: you can use just the militaryToTweleveHourConverter or take the guts out of the parseTime variable. However, I'm formatting a date from a database with date-fns then passing that formatted date to the converter.

Totally works. Hope this helps.

import dateFns from 'date-fns';


    
//* +---------------------------+
//* Format ex. Sat 1/1/18 1:00pm
//* +---------------------------+
const formatMonthDayYearTime = date =>
  militaryToTweleveHourConverter(
    dateFns.format(new Date(date), 'ddd M/DD/YY H:mm')
  );

//* +-------------------------------+
//* Convert MILITARY TIME to 12 hour
//* +-------------------------------+
const militaryToTweleveHourConverter = time => {
  const getTime = time.split(' ');

  const parseTime = getTime.map(res => {
    // Check for correct time format and split into components or return non-time units unaltered
    let timeUnit = res
      .toString()
      .match(/^([\d]|[0-1]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [res];

    console.log('timeUnit', timeUnit);
    // If the time format is matched, it will break the components into an array
    // ie. ["19:00", "19", ":", "00", undefined]
    if (timeUnit.length > 1) {
      // Remove full string match value
      timeUnit = timeUnit.slice(1);
      // Set am/pm and assign it to the last index in the array
      timeUnit[5] = timeUnit[0] < 12 ? 'am' : 'pm';
      // Adjust hours by subtracting 12 from anything greater than 12 and replace the value in the hours index
      timeUnit[0] = timeUnit[0] % 12 || 12;
    }
    // return adjusted time or original string
    return timeUnit.join('');
  });
  // Re-assemble the array pieces into a string
  return parseTime.join(' ');
};


console.log(formatMonthDayYearTime('Sat 9/17/18 18:30'));
// console log returns the following
// Mon 9/17/18 6:30pm

console.log(militaryToTweleveHourConverter('18:30'));
// console log returns the following
// 6:30pm

console.log(militaryToTweleveHourConverter('18:30:09'));
// console log returns the following
// 6:30:09pm

console.log(militaryToTweleveHourConverter('8:30:09'));
// console log returns the following
// 8:30:09am

Solution 17 - Javascript

function timeformat(date1) {
  var date=new Date(date1);
  var month = date.toLocaleString('en-us', { month: 'long' });
  var mdate  =date.getDate();
  var year  =date.getFullYear();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = mdate+"-"+month+"-"+year+" "+hours + ':' + minutes + ' ' + ampm;
  return strTime;
}
var ampm=timeformat("2019-01-11 12:26:43");
console.log(ampm);

Here the Function to Convert time into am or pm with Date,it may be help Someone.

Solution 18 - Javascript

function Time_Function() {
var date = new Date()
var time =""
var x= "AM"
if(date.getHours() >12){
    x= "PM"
}
time= date.getHours()%12 + x +":"+ date.getMinutes() +":"+ date.getSeconds()
}

Solution 19 - Javascript

function timeConversion(s) {
    let hour = parseInt(s.substring(0,2));
    hour = s.indexOf('AM') > - 1 && hour === 12 ? '00' : hour;
    hour = s.indexOf('PM') > - 1 && hour !== 12 ? hour + 12 : hour;
    hour = hour < 10 && hour > 0 ? '0'+hour : hour;

    return hour + s.substring(2,8);
}

Solution 20 - Javascript

i'm using the Temporal Polyfill now: https://github.com/js-temporal/temporal-polyfill#readme

this is as simple as:

import { Temporal } from '@js-temporal/polyfill';
myDate = "2022-04-09T14:23:27.357Z"
Temporal.Instant.from(myDate).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric' });
=> 5:23 PM // its also converting it to my browser's time zone

and if you change 'en-US' to 'de-DE' you'll get 24h instead

Solution 21 - Javascript

if you need to get time without seconds at the output

const convertTime24to12 = (time24h) => {
  let time = time24h
    .toString()
    .match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time24h];

  if (time.length > 1) {
    time = time.slice(1, -1);
    time[5] = +time[0] < 12 ? ' am' : ' pm';
    time[0] = +time[0] % 12 || 12;
  }
  return time.join(''); 
};

15:40:00

console.log(convertTime24to12("13:40:00"));

03:40

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimView Question on Stackoverflow
Solution 1 - JavascriptHBPView Answer on Stackoverflow
Solution 2 - JavascriptbbsimonbbView Answer on Stackoverflow
Solution 3 - Javascriptgilly3View Answer on Stackoverflow
Solution 4 - JavascriptHugoView Answer on Stackoverflow
Solution 5 - JavascriptDanil ValovView Answer on Stackoverflow
Solution 6 - JavascriptkvadityaazView Answer on Stackoverflow
Solution 7 - JavascriptLouInALView Answer on Stackoverflow
Solution 8 - Javascriptakhil singhalView Answer on Stackoverflow
Solution 9 - JavascriptMirza HayatView Answer on Stackoverflow
Solution 10 - JavascriptavcView Answer on Stackoverflow
Solution 11 - JavascriptBoualem DairiView Answer on Stackoverflow
Solution 12 - JavascriptSanu Uthaiah BolleraView Answer on Stackoverflow
Solution 13 - JavascriptSandeep RanjanView Answer on Stackoverflow
Solution 14 - JavascriptDrBojingleView Answer on Stackoverflow
Solution 15 - JavascriptSachinView Answer on Stackoverflow
Solution 16 - JavascriptjameygleasonView Answer on Stackoverflow
Solution 17 - JavascriptRahul SainiView Answer on Stackoverflow
Solution 18 - JavascriptGunjan KumarView Answer on Stackoverflow
Solution 19 - JavascriptdawidekView Answer on Stackoverflow
Solution 20 - JavascriptAzeer EsmailView Answer on Stackoverflow
Solution 21 - JavascriptIvan K.View Answer on Stackoverflow