Store Hours: Display Current Time and Holidays - javascript

So, I'm working to add store hours to a particular site. I found this great bit of JS that displays the current time when the page loads and identifies whether or not the store is closed. However, I would like to change the time captured at time of page loading to an active clock. I'm hoping someone can assist.
When the page loads, it displays the time at which the page loads. i.e. Visit site at 12:30PM, timeDiv displays 12:30PM. At 12:31PM, it still displays 12:30PM.
What I would like instead is an active clock, so that at 12:31PM it displays 12:31PM and displays the current time at each interval after that.
Here's the link to the original Pen: https://codepen.io/zeinab92/pen/xwWGWM
var now = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var checkTime = function() {
var today = weekday[now.getDay()];
var timeDiv = document.getElementById('timeDiv');
var dayOfWeek = now.getDay();
var hour = now.getHours();
var minutes = now.getMinutes();
//add AM or PM
var suffix = hour >= 12 ? "PM" : "AM";
// add 0 to one digit minutes
if (minutes < 10) {
minutes = "0" + minutes; }
if ((dayOfWeek === 1 || dayOfWeek === 2 || dayOfWeek === 3 || dayOfWeek === 4 || dayOfWeek === 5) && hour >= 9 && hour === 17 && minutes <=29) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
timeDiv.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
timeDiv.className = 'open';
}
else if ((dayOfWeek === 6) && hour >= 8 && hour === 15 && minutes <= 59) {
hour = ((hour + 11) % 12 + 1);
timeDiv.innerHTML = '<p id="hour">it\'s ' + today + ' ' + hour + ':' + minutes + suffix + '</p> <p id="stat">we\'re open!</p>';
timeDiv.className = 'open';
}
else {
if (hour === 0 || hour > 12) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
}
timeDiv.innerHTML = '<p id="hour">It\'s ' + today + ' ' + hour + ':' + minutes + suffix + '</p><p id="stat">we\'re closed!</>';
timeDiv.className = 'closed';
}
};
var currentDay = weekday[now.getDay()];
var currentDayID = "#" + currentDay; //gets todays weekday and turns it into id
$(currentDayID).toggleClass("today"); /hightlights today in the view hours modal popup
setInterval(checkTime, 1000);
checkTime();

There is a very popular library for JavaScript called momentjs and it handles a lot of date/time logic nicely. I'd recommend you start there.
This code extends momentjs in much the same way you'd need to put into your holidays:
https://gist.github.com/jrhames/5200024
The basic logic is to track your holidays in a separate custom array then create a function that takes a date as a parameter and does a lookup into your array of holidays.

Related

How to display when closed or open javascript

I am using the following code from https://codepen.io/zeinab92/pen/xwWGWM
How can I edit the javascript so the opening times are as following:
Monday 6am–1am
Tuesday 6am–1am
Wednesday 6am–1am
Thursday 6am–1am
Friday 6am–1am
Saturday 8am–6pm
Sunday 10am–4pm
I have tried doing the following however when i visit the webpage it still says that 'We're closed' (monday) although I already set the day of the weeks and hours. I have a feeling that the else statement might be conflicting with it.
Can anyone help please
var now = new Date();
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
....
....
....
....
if ((dayOfWeek == 1 || dayOfWeek == 2 || dayOfWeek == 3 || dayOfWeek == 4 || dayOfWeek == 5) && hour >= 6 && hour <= 0) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
timeDiv.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
timeDiv.className = 'open';
}
else if ((dayOfWeek == 6) && hour >= 8 && hour <= 18) {
hour = ((hour + 11) % 12 + 1);
timeDiv.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
timeDiv.className = 'open';
}
else if ((dayOfWeek == 0) && hour >= 10 && hour <= 16) {
hour = ((hour + 11) % 12 + 1);
timeDiv.innerHTML = 'it\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re open!';
timeDiv.className = 'open';
}
else {
if (hour == 0 || hour > 12) {
hour = ((hour + 11) % 12 + 1); //i.e. show 1:15 instead of 13:15
}
timeDiv.innerHTML = 'It\'s ' + today + ' ' + hour + ':' + minutes + suffix + ' - we\'re closed!';
timeDiv.className = 'closed';
}
};
....
...
...
...
Your first if is incorrect as you are checking that hour is >= 6 and <= 0
use next one
if( ([1,2,3,4,5].indexOf(dayOfWeek) >= 0) &&
((hour >= 6 && hour <= 23) || hour == 0) ) { ... }
In following if statements you also have things like <= 18. That will also include 18:30h, everything until 18:59
I agree with the answers and comments above, this should really be a server side calculation.
However, the issue lies with your code for the first if statement, particularly this section:
hour >= 6 && hour <= 0
It is physically impossible for the hour to be more than or equal to 6, but also less than or equal to 0, therefore it is completely ignoring that section and moving down to the final else statement.
My recommendation for this would be to change this section to:
((hour >= && hour <= 23) || hour == 0)

Solving a time and day issue

I don't understand how this works. can someone explain it to me? Especially the variable name "prepand" which I've seen as "prepend" when I look it up. Also, what does the ? mean in (hour>12)?
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday","Monday","Tuesday","Wednesday
","Thursday","Friday","Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12)? " PM ":" AM ";
hour = (hour >= 12)? hour - 12: hour;
if (hour===0 && prepand===' PM ')
{
if (minute===0 && second===0)
{
hour=12;
prepand=' Noon';
}
else
{
hour=12;
prepand=' PM';
}
}
if (hour===0 && prepand===' AM ')
{
if (minute===0 && second===0)
{
hour=12;
prepand=' Midnight';
}
else
{
hour=12;
prepand=' AM';
}
}
console.log("Current Time : "+hour + prepand + " : " + minute + " : " + second);
var prepand = (hour >= 12)? " PM ":" AM ";
This translates to:
var prepand;
if (hour >= 12){
prepand = "PM";
} else {
prepand = "AM";
}
This writing is a shorthand expression called ternary. It is used to assign conditional values to variables in this case.
That is a basic code which gets the current date and tell you the day and time by manipulating the date. Check the comments corresponding to the lines.
Prepand variable is used to add the AM/PM with the time
Read here in details about Date
var today = new Date(); //Creates a JavaScript Date instance that represents a single moment in time
var day = today.getDay(); // return the index of the day
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ","Thursday","Friday ","Saturday "];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();// getHours() method returns the hour for the specified date
var minute = today.getMinutes();//getMinutes() method returns the minutes in the specified date
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour; //? is a part of ternary operator which will check if hour >=12 or not. If >= then prepand in PM otherwise AM
if (hour === 0 && prepand === ' PM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Noon';
} else {
hour = 12;
prepand = ' PM';
}
}
if (hour === 0 && prepand === ' AM ') {
if (minute === 0 && second === 0) {
hour = 12;
prepand = ' Midnight';
} else {
hour = 12;
prepand = ' AM';
}
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " +
second);

How to set Am and Pm for Clock [duplicate]

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>

Page last modified using Javascript with 12 hour clock showing am or pm

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;
}

Compare hardcoded date with the current date

I am trying to compare dates in javascript.
I have a hardcoded date (03/23/2015 11:20 am) in of , and I am trying to compare it with the current date in the same format.
But I am always getting it as not same.
function formatDate(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 date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var timeNow = formatDate(D);
var startTime6 = document.getElementById('tno6_time').innerHTML;
if (timenow == startTime6) {
alert("Same");
}
else {
alert("not same");
}
Your's javascript portion :
var d = new Date();
var timeNow = formatDate(D);
if (timenow == startTime6) {
alert("Same");
}
Here check in above code you are creating variable with name d and you are passing variable D which is not declared.Here you have also typo in timeNow not timenow.It should be like
var timeNow = formatDate(d);
if (timeNow == startTime6) {
alert("Same");
}
Apart from that check both the variables value either with console.log() function or with alert() and see if there are same then It should alert the 'Same' else 'not same'.
And keep in mind new Date() will always give you current time so if you are comparing with hard coded date then Only once there are the possibility that result should come 'Same' and It will only occur when you are executing this code when the hard coded date and time exactly the same.
It is very hard to check your code in that way because millisecond change will affect your result.
Check this demo

Categories

Resources