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)
Related
Is you'll probably be able to tell I'm a complete JS rookie but I've spent my day working on this code to display a shipping timer, compiled from bits of various other posts on SO (thanks!).
It seemed to be going well until I completed adding all the functionality I needed and now it's not working. When you first run the snippet it works correctly but as soon as it ticks the "day" value displays incorrectly (it should display 'tomorrow' but it switches to 'today') and the timer itself has stopped counting down.
I can't figure out for the life of me where I messed it up so looking for some assistance if possible! Thanks in advance.
JSFiddle: http://jsfiddle.net/c3otusv6/
(function() {
var start = new Date();
start.setHours(14, 0, 0);
var maybePluralize = function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
var now = new Date();
var day = now.getDay();
function tick() {
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var hh = Math.floor(remain / 60 / 60 % 60);
var mm = Math.floor(remain / 60 % 60);
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + "</strong>";
setTimeout(tick, 1000);
}
}
document.addEventListener('DOMContentLoaded', tick);
})();
If you need to have the function called every second, you need to use setInterval. setTimeout just runs the given function once after the specified number of seconds.
I have made small edit to you fiddle, to make it run every second.
As for the "day" value being incorrect, I think you need to check your if statements. I quite dont understand your business logic.
Also note - Sunday is given by '0' in getDay. And I see you using day == 7, so you might want to check that and do the necessary adjustments. I guess you need to -1 from all your if statements for day.
http://jsfiddle.net/wm9kj8yb/
(function() {
var start = new Date();
var now = new Date();
var day = now.getDay();
start.setHours(14, 0, 0);
function maybePluralize(count, noun) {
var suffix = arguments.length <= 2 || arguments[2] === undefined ? 's' : arguments[2];
return count + ' ' + noun + (count !== 1 ? suffix : '');
};
function tick() {
now = new Date();
day = now.getDay();
if (day >= 1 && day <= 5 && now < start) {
document.getElementById('ddate').innerHTML = 'today';
} else if (day >= 1 && day <= 4 && now >= start || day == 7) {
document.getElementById('ddate').innerHTML = 'tomorrow';
} else if (day == 5 && now >= start || day == 6) {
document.getElementById('ddate').innerHTML = 'Monday';
}
if (day == 6 || day == 5 && now > start || day == 7 && now < start) {
document.getElementById('countdown').innerHTML = "now";
} else {
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = (start - now) / 1000;
var ss = Math.floor(remain % 60);
remain = Math.floor(remain / 60);
var mm = remain % 60;
remain = Math.floor(remain / 60);
var hh = remain % 60;
document.getElementById('countdown').innerHTML = "in the next <strong>" + maybePluralize(hh, 'hour') + " " + maybePluralize(mm, 'min') + " " + " " + maybePluralize(ss, 'sec') + "</strong>";
}
}
document.addEventListener('DOMContentLoaded', function() {
setInterval(tick, 1000);
});
})();
Order <span id='countdown'></span> for dispatch <span id='ddate'></span>
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 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);
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.
I'm using Angularjs and would like to know how can I display a date in this "format"
member for : 1 year, 10 months
Is there a Javascript/Jquery/Angularjs built-in function that is doing it or should I calculate it myself.
Thank you
You could create your own filter which wraps .fromNow() in moment.js.
filter('timeago', function() {
return function(datetime) {
return moment(datetime).fromNow();
};
})
Then you can use it like any other angular filter;
{{ "2014-01-01T12:00:00" | timeago }}
Demo
Since I didn't find exactly what I was looking for I did it myself.
So this function returns the time passed between two dates.
Date.prototype.from = function(pastDate, presentDate){
var presentDate = (typeof presentDate === "undefined") ? this : presentDate;
//the string to return.
var dateString = "";
var minute = 60 * 1000,
hour = minute * 60,
day = hour * 24,
month = day * 30,
year = month * 12,
ms = Math.abs(presentDate - pastDate);
var years = parseInt(ms / year, 10);
ms -= years * year;
var months = parseInt(ms / month, 10);
ms -= months * month;
var days = parseInt(ms / day, 10);
ms -= days * day;
var hours = parseInt(ms / hour, 10);
ms -= hours * hour;
var minutes = parseInt(ms / minute, 10);
if(months <= 0 && days <= 0 && hours <= 0 && minutes <= 0){
dateString = "1 minute";
return dateString;
}
if(years > 0){
if(years == 1){
dateString += years + " year";
}else{
dateString += years + " years";
}
if(months > 0){
if(months == 1){
dateString += ", " + months + " month";
}else{
dateString += ", " + months + " months";
}
}
//year = 0
}else{
if(months > 0){
if(months == 1){
dateString += months + " month";
}else{
dateString += months + " months";
}
if(days > 0){
if(days == 1){
dateString += ", " + days + " day";
}else{
dateString += ", " + days + " days";
}
}
//month = 0
}else{
if(days > 0){
if(days == 1){
dateString += days + " day";
}else{
dateString += days + " days";
}
if(hours > 0){
if(hours == 1){
dateString += ", " + hours + " hour";
}else{
dateString += ", " + hours + " hours";
}
}
//days = 0
}else{
if(hours > 0){
if(hours == 1){
dateString += hours + " hour";
}else{
dateString += hours + " hours";
}
if(minutes > 0){
if(minutes == 1){
dateString += minutes + " minute";
}else{
dateString +=", " + minutes + " minutes";
}
}
//hours = 0
}else{
if(minutes > 0){
if(minutes == 1){
dateString += minutes + " minute";
}else{
dateString += minutes + " minutes";
}
}
}
}
}
}
return dateString
}
USAGE
// now
var now = new Date();
var d1 = new Date("October 13, 1995 11:13:00")
var d2 = new Date("March 13, 2005 11:13:00")
// from now
alert( now.from( d1 ) )
// time elapsed between two dates
alert( now.from( d1, d2 ) )
FIDDLE