This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
var timeNow = new Date();
var hours = time.getHours() > 12 ? time.getHours() - 12 : time.getHours();
hours = hours < 10 ? "0" + hours : hours;
function functionHours(){
if(hours > 12) {
return (time.getHours()-12)
} else {
if(hours < 10 && hours > 12) {
return ("0" + hours)
} else {
return (hours)
} else {
return (time.getHours())
}
}
}
I would to convert the ternary operations into if else statements, I've stored the statements on the functions unfortunately it returns an error unexpected token else. What I would like to do is to add 0 to the hours if the hour is 1-9 (E.g. 09, 08, 05, etc...) What seems to be the problem?
Simply make it
var hours = time.getHours();
if (hours < 12)
{
hours = ("0" + hours).slice(-2);
}
No need to check for scenario where hours is greater than 12 at all.
Your logic is off, the following will never be true, because hours can't simultaneously be less than 10 and greater than 12 at the same time:
hours < 10 && hours > 12
Try this version, which is a close conversion of your original ternary expression:
function functionGetHours12(hours) {
if (hours > 12) {
hours = hours - 12
}
if (hours < 10) {
return ("0" + hours)
}
else {
return hours;
}
}
console.log("hour 1: " + functionGetHours12(1));
console.log("hour 9: " + functionGetHours12(9));
console.log("hour 10: " + functionGetHours12(10));
console.log("hour 12: " + functionGetHours12(12));
console.log("hour 15: " + functionGetHours12(15));
console.log("hour 23: " + functionGetHours12(23));
Please check the converted ternary operator to if-else and function:
function functionHours(){
var time = new Date();
var hours = time.getHours() > 12 ? time.getHours() - 12 : time.getHours();
if (time.getHours() > 12) {
hours = time.getHours() - 12;
}
else {
hours = time.getHours();
}
if(hours < 10) {
return "0" + hours;
}
else {
return hours;
}
}
console.log(functionHours());
Related
I'm trying to build a program which converts military hours to am or pm time.
I expected the output of 0 to be 12 am, but the actual output is 0 am.
const militaryHour = 0;
var hour = 0;
var amOrPm = "am";
if (militaryHour < 12) {
hour = militaryHour;
console.log(hour + " " + amOrPm);
} else if (militaryHour == 12) {
amOrPm = "pm";
hour = 12;
console.log(hour + " " + amOrPm);
} else if (militaryHour < 24) {
amOrPm = "pm";
hour = militaryHour - 12;
console.log(hour + " " + amOrPm);
} else if (militaryHour == 24){
hour = 12;
console.log(hour + " " + amOrPm);
} else {
hour = 12;
console.log(hour + " " + amOrPm);
}
All the code you need
const militaryHour = 0,
hour = (militaryHour + 11) % 12 + 1,
amOrPm = militaryHour % 24 < 12 ? 'am' : 'pm';
No if/else required
Let's follow your logic
const militaryHour = 0;
if (militaryHour < 12)
Ok definitely goes into this if statement because 0<12
hour = militaryHour;
console.log(hour + " " + amOrPm);
Then log whatever militaryHour is, which is 0. This is why your code is printing "0 am"
12am is actually an edge case. You just need to add one more condition
if (militaryHour==0) {
hour = 12;
console.log(hour+" "+amOrPm)
}
In your code, the first branch, if (militaryHour < 12) {...} is true, so we have:
const militaryHour = 0;
var hour = 0;
var amOrPm = "am";
hour = militaryHour;
console.log(hour + " " + amOrPm);
It's pretty clear that we're going to get 0 from this.
Here's a solution: take the 24-hour time mod 12. If we wind up with 0, make it 12. Either way, append A.M./P.M. depending on which half of the day the time falls into. All of this eliminates the error-prone large conditional blocks.
const militaryToNormal = hour =>
(hour % 12 || 12) + (hour % 24 < 12 ? "am" : "pm")
;
for (let i = 0; i < 30; i++) {
console.log(i, "=>", militaryToNormal(i));
}
If you can, prefer moment.js.
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'm trying to create a script in Javascript that shows when a page was last modified, which returns the date, time, in am or pm format, of modification.
Clearly I am doing something wrong. I can't get the script to run, and it will be in my function AmPm. Can someone please help?
// Javascript code for page modification
// Shows the date, time, am or pm, of modification.
// This section sets the date of modification
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "." + (modiDate.getMonth() + 1) + "." + modiDate.getFullYear();
return showAs
}
// This section sets the time of modification
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
// This section writes the above in the document
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
// This section decides if its am or pm
function AmPm() {
var hours = new Date().getHours();
var hours = (hours + 24 - 2) % 24;
var mid = 'AM';
if (hours == 0) { // At 00 hours (midnight) we need to display 12 am
hours = 12;
} else if (hours > 12) // At 12pm (Midday) we need to display 12 pm
{
hours = hours % 12;
mid = 'PM';
}
}
var mid = //This is where I am stuck!!
return AmPm
document.write("This webpage was last edited on: ");
document.write(lastModified() + " at " + GetTime() + AmPm());
document.write("");
document.write(" NZ Daylight Savings Time.");
document.write("");
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;
}
I want a js script that converts inputted time to 24 hour format or 12 hour format.
Example,
time is entered as 10_10_am result should be:-
10:10 AM (12 hr format) and 10:10 (24 hr format)
time is entered as 10_10_pm result should be:-
10:10 PM (12 hr format) and 22:10 (24 hr format)
HTML
<input type="text" id="textbox1"/>
<input type="button" id="b1" value="convert 12 hr"/>
<input type="button" id="b2" value="convert 24 hr"/>
<div id="result"></div>
JS
$(document).ready(function () {
function am_pm_to_hours(time) {
console.log(time);
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;
return (sHours +':'+sMinutes);
}
function hours_am_pm(time) {
var hours = time[0] + time[1];
var min = time[2] + time[3];
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours.length < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}
$('#b1').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = hours_am_pm(n1[0]+n1[1]);
$('#result').text(time);
});
$('#b2').click(function(){
var n = $('#textbox1').val();
var n1 =n.split('_');
var time = am_pm_to_hours(n1[0]+':'+n1[1]+' '+n1[2]);
$('#result').text(time);
});
});
Working Demo http://jsfiddle.net/cse_tushar/xEuUR/
updated after Adrian P 's comment
Working Demo http://jsfiddle.net/cse_tushar/xEuUR/4
function hours_am_pm(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var min = Number(time.match(/:(\d+)/)[1]);
if (min < 10) min = "0" + min;
if (hours < 12) {
return hours + ':' + min + ' AM';
} else {
hours=hours - 12;
hours=(hours < 10) ? '0'+hours:hours;
return hours+ ':' + min + ' PM';
}
}
I am not sure if there is any specific function that already exists, but this is fairly easy to write.
Considering your input is always ##_##_pm or ##_##_am you can split this string on every _ and grab first value as hours, second as minutes and compare the third
and
if it's pm add 12 hours to the hours variable for 24 hr format.
You need a function that takes 2 parameters (format and string)
It will look something like this:
function timeFormat(format, str){
var timeParts=str.split("_");
if(format==12){
return timeParts[0] + ":" + timeParts[1] + " " + timeParts[2];
}else if(format == 24){
var hours = timeParts[0];
if(timeParts[2] == "pm")
hours += 12;
return hours + ":" + timeParts[1]
}
}
i have an if statement to change time back to 12 after it hits 11:45:
i = (i >= 192) ? i - 192 : ( i >= 96) ? i - 96 : i
var mins = (i * 15 % 60)
var hours = Math.floor(i * 15 / 60)
var ampm = (hours >= 12) ? "PM" : "AM"
hours = (hours == 0) ? 12 : (hours >= 12) ? hours - 12 : hours;
var nextMins, nextHours = hours;
switch (mins) {
case 0:
mins = "";
nextMins = 15;
break;
case 45:
nextMins = "";
nextHours = hours+1;
break;
default:
nextMins = mins + 15;
break;
}
var time = hours + (mins == "" ? "" : ":" + mins) + " - " + nextHours + (nextMins == "" ? "" : ":" + nextMins) + ampm
it changes in 15 minute intervals, the issue is it will start at 12 but after it gets to 12:00 again it will display as 0:15, 0:30, 0:45. Instead of 12:15, 12:30, 12:45
I thought this part of the if statement would do it:
hours = (hours == 0) ? 12
but isn't working?
The simplest way is probably
hours = (hours % 12) || 12;
This way copes with any positive integer for hours (eg. 36 will still return 12).
It should read
hours = (hours == 0) ? 12 : (hours > 12) ? hours - 12 : hours;
By having >= you're currently including 12 as a number to deduct 12 from.
hours = (hours == 0) ? 12 : hours;
is the complete usage of ternary conditional. But why don't you use a simple if statement?
if(hours == 0)
hours = 12;