I'm using Vue.
How can I convert my 24-hour time to 12-hour time when it's a string, not a date object?
For example, I need to convert "17:30" to 5:30pm.
I'm adding multiple variations of start and end times for different formatting needs: text messages, vuetify calendar, etc.
const timeAmPm=s=>s.split(':').reduce((a,c)=>a?(s===a+c)?a+c+'am':a+c+'pm':c%12+':','')
console.log(timeAmPm('17:30')) // 5:30pm
console.log(timeAmPm('10:30')) // 10:30am
Try it, it works for both - String or Date instance.
function formatAMPM(date) {
if (typeof date === "string") {
let [hours, minutes] = date.split(":");
let ampm = "AM";
if (Number(hours) > 12) {
hours = Number(hours) - 12;
ampm = "PM";
}
return `${hours}:${minutes} ${ampm}`;
} else if (date instanceof Date) {
let hours = date.getHours();
let minutes = date.getMinutes();
let ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
let strTime = hours + ":" + minutes + " " + ampm;
return strTime;
}
return date;
}
console.log(formatAMPM(new Date()))
console.log(formatAMPM('20:20'))
Related
I want to know in this code what is the meaning of the line of code asked in the question why this code is used. Can you tell me what the meaning of this line is? I wonder what the use of this line is.
$(document).ready(function () {
function showTime() {
// To Get the current time/date
var date = new Date();
//Make Variables to get hours, minute, and second
var hours = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
// AM, PM Setting
var session = "AM";
// Conditions for time behavior
if (hours == 00) {
hours = 12;
}
if (hours >= 12) {
session = "PM";
}
if (hours > 12) {
hours = hours - 12;
}
hours = hours < 10 ? "0" + hours : hours;
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
// Set the variable to span
$("#hours").text(hours);
$("#min").text(min);
$("#sec").text(sec);
$("#period").text(session);
// To change time in every seconds
setTimeout(showTime, 1000);
}
showTime();
});
If the hour is 00, meaning 12 in the morning (midnight), it changes the string value to show '12' instead of '00', in order to display the time in 12-hour format.
I want to convert a 12-hour format time into a string, add some minutes, then convert back to string. My user will be entering a time as a sting example 8:03 AM this time needs to converted into an integer with 9 minutes added to it then converted back to the same 12-hour format just 9 minutes into the future.
I've tried to make a Date obj using the string time, but when I do the Date constructor says I am using an invalid date.
new Date("8:03 AM")
What I tried after that was adding a speicifc date to the time
new Date("09/10/2022 8:03 AM")
That worked to create a Date obj and then I would try to get just the time using .getTime() and pass that into my intToHHMM function.
const intToHHMM = function (time) {
var sec_num = parseInt(time, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes;
}
But I am getting a weird return that definitely is not hh:mm format.
Can someone lend a hand, I appreciate the help in advance!
check this function, pass any time and it will add minsToAdd minutes to start. Correct any mistakes when see them.
function addMins(start, minsToAdd) {
let am_pm = start.split(" ")[1]
let [hr, min] = start.split(" ")[0].split(":")
let future = ""
min = parseInt(min) + minsToAdd
if (min > 59) {
min = min - 60
hr = parseInt(hr) + 1
am_pm = hr > 11 ?
am_pm === "PM" ? "AM" : "PM" :
am_pm === "AM" ? "PM" : "AM";
hr = hr > 12 ? hr - 12 : hr;
future = [
`${parseInt(hr)}`.length === 1 ? `0${hr}` : `${hr}`,
`${min}`.length === 1 ? `0${min}` : `${min}`,
am_pm
].join(":")
} else {
future = [`${hr}`.length === 1 ? `0${hr}` : `${hr}`,
`${min}`.length === 1 ? `0${min}` : `${min}`,
am_pm
].join(":")
}
return future
}
console.log(addMins("11:56 AM", 9)) //12:05:PM
console.log(addMins("11:56 PM", 9)) //12:05:AM
console.log(addMins("19:03 PM", 9)) //19:12:PM
You don't need to involve Date methods here, just some magic:
const add9 = HM12 => {
let [H, M, ampm] = HM12.split(/\W/);
let minutes = (H % 12 + 12 * (ampm === 'PM')) * 60 - -M;
minutes += 9; // magic
M = (minutes % 60 + '').padStart(2, 0);
H = minutes / 60 % 24|0;
ampm = H < 12 ? 'AM' : 'PM';
H = (H % 12 + '' || '12').padStart(2, 0);
return `${H}:${M} ${ampm}`;
}
console.log('08:03 AM --> ' + add9('08:03 AM'))
console.log('11:53 PM --> ' + add9('11:53 PM'))
console.log('11:53 AM --> ' + add9('11:53 AM'))
Just check this out. Modified for time input.
calc.addEventListener("click", function() {
var time = document.getElementById("time").value
var date=new Date();
if(time){
date = new Date(date.toLocaleDateString('en-US')+" "+time);
}
var options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
var timePlusNineMinString=addMinutes(date,9).toLocaleString('en-US', options);
console.log(timePlusNineMinString);
})
Time:<input id="time" type="time" name="task_time" />
<button id="calc">Get Time</button>
I need to create strings in javascript that contain the current time.
How can I create two strings like the following, but with the current timestamp?
itemTimestamp = "Itemized at 2014-05-01, 11:11 PM"
itemFilename = "itemized_at_2014_05_01_11_11_pm.png"
JSFIDDLE:
http://jsfiddle.net/gkQ7y/9/
function format(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
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'
hours = hours < 10 ? '0' + hours : hours; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime ="Itemized at "+year+"-"+month+"-"+day+", "+hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var d = new Date();
document.getElementById("test1").innerHTML = format(d);
var replaced = format(d).replace(/[ :-]/g,"_").replace(",","");
document.getElementById("test2").innerHTML = replaced+".png";
I have buttons with the names of big cities.
Clicking them, I want to get local time in them.
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = hours-2; //this is the distance from my local time
alert ('Toronto time: ' + hours + ' h'); //this works correctly
});
But how can I get AM or PM ?
You should just be able to check if hours is greater than 12.
var ampm = (hours >= 12) ? "PM" : "AM";
But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.
Try below code:
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = (hours+24-2)%24;
var mid='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='pm';
}
alert ('Toronto time: ' + hours + mid);
});
You can use like this,
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
Hopes this will be better with minutes too.
const now = new Date()
.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
.toLowerCase();
Basically you just need to put {hour12: true} and it's done.
result => now = "21:00 pm";
If hours is less than 12, it's the a.m..
var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
am;
// adjust for timezone
hours = (hours + 24 - 2) % 24;
// get am/pm
am = hours < 12 ? 'a.m.' : 'p.m.';
// convert to 12-hour style
hours = (hours % 12) || 12;
Now, for me as you didn't use getUTCHours, it is currently 2 hours after
hours + ' ' + am; // "6 p.m."
very interesting post. in a function that take a date in parameter it can appear like that :
function hourwithAMPM(dateInput) {
var d = new Date(dateInput);
var ampm = (d.getHours() >= 12) ? "PM" : "AM";
var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();
return hours+' : '+d.getMinutes()+' '+ampm;
}
with date.js
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
you can write like this
new Date().toString("hh:mm tt")
cheet sheet is here format specifiers
tt is for AM/PM
Try this:
h = h > 12 ? h-12 +'PM' : h +'AM';
The best way without extensions and complex coding:
date.toLocaleString([], { hour12: true});
How do you display javascript datetime in 12 hour AM/PM format?
here is get time i use in my code
let current = new Date();
let cDate = current.getDate() + '-' + (current.getMonth() + 1) + '-' + current.getFullYear();
let hours = current.getHours();
let am_pm = (hours >= 12) ? "PM" : "AM";
if(hours >= 12){
hours -=12;
}
let cTime = hours + ":" + current.getMinutes() + ":" + current.getSeconds() +" "+ am_pm;
let dateTime = cDate + ' ' + cTime;
console.log(dateTime); // 1-3-2021 2:28:14 PM
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
return timewithampm;
var dt = new Date();
var h = dt.getHours(),
m = dt.getMinutes();
var time;
if (h == 12) {
time = h + ":" + m + " PM";
} else {
time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
}
//var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
console.log(`CURRENT TIME IS ${time}`);
This will work for everytime,
function Timer() {
var dt = new Date()
if (dt.getHours() >= 12){
ampm = "PM";
} else {
ampm = "AM";
}
if (dt.getHours() < 10) {
hour = "0" + dt.getHours();
} else {
hour = dt.getHours();
}
if (dt.getMinutes() < 10) {
minute = "0" + dt.getMinutes();
} else {
minute = dt.getMinutes();
}
if (dt.getSeconds() < 10) {
second = "0" + dt.getSeconds();
} else {
second = dt.getSeconds();
}
if (dt.getHours() > 12) {
hour = dt.getHours() - 12;
} else {
hour = dt.getHours();
}
if (hour < 10) {
hour = "0" + hour;
} else {
hour = hour;
}
document.getElementById('time').innerHTML = hour + ":" + minute + ":" + second + " " + ampm;
setTimeout("Timer()", 1000);
}
Timer()
<div id="time"></div>
I would like to get this format:
2:18:00 pm
Using the sample code from w3Schools.com below, I can get the correct results from IE and FireFox. But when it comes to Chrome, I get the 24hr clock version where it is simply displayed this way:
14:18:00
In FF
new Date().toLocaleTimeString()
// 2:18:00 pm
function twoDigitPad(number) {
return ("0" + number).slice(-2);
}
function twelveHourTimeString() {
var date = new Date();
var hour = date.getHours();
var min = twoDigitPad(date.getMinutes());
var sec = twoDigitPad(date.getSeconds());
var ampm = hour < 12 ? "am" : "pm";
hour = hour % 12 || 12; // convert to 12-hour format
return hour + ":" + min + ":" + sec + " " + ampm;
}
date.getHours() returns an integer between 0 and 23, which hour % 12 || 12 converts to the 12-hour format.
date.getMinutes() and date.getSeconds() each return an integer, so you'll need to zero-pad those values when they're less than 10. Optionally, hour as well.
Use the following javascript code,
<script type="text/javascript">
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
if (curr_hour < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
document.write(curr_hour + ":" + curr_min + ":"
+ curr_sec+ a_p);
</script>
The o/p would be as you expect,2:18:00 PM
Dealing with dates reliably cross-browser is a ball-ache in javascript- I would use the DateFormat library; http://blog.stevenlevithan.com/archives/date-time-format
then as he notes on the page, you can call it like so;
dateFormat(now, "h:MM:ss TT");
There are a few alternatives, but this one seems the most light-weight.