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 Javasc
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
}
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'))
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}`;
}
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"
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>
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/