Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone
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>
Converting 24 hour time to 12 hour time w/ AM & PM using Javascript
UPDATE 2: without seconds option
UPDATE: AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/
I created this function to do this:
function formatDate(date) { var d = new Date(date); var hh = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var dd = "AM"; var h = hh; if (h >= 12) { h = hh - 12; dd = "PM"; } if (h == 0) { h = 12; } m = m < 10 ? "0" + m : m;
s = s < 10 ? "0" + s : s;
/* if you want 2 digit hours: h = h<10?"0"+h:h; */
var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);
var replacement = h + ":" + m; /* if you want to add seconds replacement += ":"+s; */ replacement += " " + dd;
return date.replace(pattern, replacement);}
alert(formatDate("February 04, 2011 12:00:00"));
Converting a 24 hour clock to a 12 hour clock and keeping track of AM/PM
You can do it like this (the item # refers to the code example so you can see exactly where it goes):
declare a variable to track am/pm
var timeAmPm = "am";
Before you reset the time to 12-hour, check if it is > 12 and set var to
am
orpm
:(hour > 12) ? timeAmPm = "pm" : timeAmPm = "am";
Use the variable as required, e.g.
var time = "Hour + " + i + ": " + hour + timeAmPm;
Working Example (using your code - except for the code accessing the HTML elements as you didn't give us those):
// get current date
var date = new Date();
// get current hours
var currentHour = date.getHours();
// for loop counter variable
var i;
// 1. declare a variable to track am/pm
var timeAmPm = "am";
console.log("Current hour: " + currentHour);
// used when currentHour + i goes past 24. (25th hour is 0).
resetCounter = 0;
for (i = 1; i < 24; i++) {
// first hour to be displayed is currentHour (now) plus i hour.
hour = currentHour + i;
// if currentHour + i is greater than or equal to 24
if (hour >= 24) {
// set hour to 0 + resetCounter
hour = 0 + resetCounter;
// increment resetCounter
resetCounter++;
}
// 2. Before you reset the time, check if it is am or pm
(hour > 12) ? timeAmPm = "pm" : timeAmPm = "am";
// convert 24 hr time to 12 hr time
hour = hour % 12;
// if hr is 0, make it show 12.
if (hour == "0") {
hour = 12;
}
// 3. Use the variable as required
console.log("Hour + " + i + ": " + hour + timeAmPm);
}
How to convert time from 24 hour format to 12 hour format using javascript?
Just use modulus 12:
function formatTimeShow(h_24) {
var h = h_24 % 12;
return (h < 10 ? '0' : '') + h + ':00';
}
Modulus (%
) means divide and take remainder. For example 17 / 12 = 1 with remainder 5. So the result of 17 % 12 is 5. And hour 17 is hour 5 in 12-hour time.
But note that this function is not complete since it doesn't work for hour 0 (or hour 12). To fix it you have to add in another check for that:
function formatTimeShow(h_24) {
var h = h_24 % 12;
if (h === 0) h = 12;
return (h < 10 ? '0' : '') + h + ':00';
}
Also note that you can add a meridian easily, by seeing whether the hour is less than 12 (am) or equal to/greater (pm):
function formatTimeShow(h_24) {
var h = h_24 % 12;
if (h === 0) h = 12;
return (h < 10 ? '0' : '') + h + ':00' + (h_24 < 12 ? 'am' : 'pm');
}
Note: All of the above is assuming the parameter to this function is an integer between 0 and 23.
How do you display JavaScript datetime in 12 hour AM/PM format?
function formatAMPM(date) {
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 = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
console.log(formatAMPM(new Date));
convert 12-hour hh:mm AM/PM to 24-hour hh:mm
Try this
var time = $("#starttime").val();
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);
Formatting 12 hour time (h:mm A) to 24 hour time (HH:mm:00) in day.js
Just prepend any date to make a valid dayjs date object
Note: this is the lazy way of allowing a time string. To adhere to the documentation of dayJS. look at the other answer
Or don't use dayJS at all
const ampm2military = ampm => ampm ? dayjs(`1/1/1 ${ampm}`).format("HH:mm:00") : null;
console.log(ampm2military("1:24 PM"));
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script>
Related Topics
Selecting Multiple Classes with Jquery
Get the Visible Height of a Div with Jquery
External Template in Underscore
Keycode Values for Numeric Keypad
Event Listener for When Element Becomes Visible
How to Use Preload.Js Properly in Electron
How to Remove an Object from an Array with JavaScript
Passing in Dynamic Key:Value Pairs to an Object Literal
Capture Click on Div Surrounding an Iframe
Get Character Value from Keycode in JavaScript... Then Trim
Spring Boot Controller - Upload Multipart and JSON to Dto
How to Verify Jquery Ajax Events with Jasmine
Jest: Timer and Promise Don't Work Well. (Settimeout and Async Function)
JavaScript 'In' Operator for 'Undefined' Elements in Arrays
Node.Js Async/Await Using with MySQL
Multiple Conditions for JavaScript .Includes() Method
Advanced JavaScript: Why Is This Function Wrapped in Parentheses