Script for business hours javascript - javascript

I need script that will display "Open" & "Close" function on my site.
Script should display "OPEN" every day from Monday to Friday from 08:00am to 19:30pm
and for Saturday should display "OPEN" from 08:00am to 15:00pm (else display CLOSED)
Sunday is CLOSED all day long.
I try to manage this script but I was not able to achieve it:
var Digital=new Date()
var hours=Digital.getHours()
if (hours>=08:00&&hours<=19:30)
document.write('Open')
else if (hours>=19:31&&hours<=07:59)
document.write('Close')
but i need addition for the days, this is just for time.

The hours variable will be an integer number, you need to compare it to a number, like this:
if (hours >= 8 && hours <= 19)
document.write('Open')
else if (hours >= 19 && hours <= 7)
document.write('Close')
When rewrite those methods, you will need to get and compare the minutes from the Digital variable too.

You need to check the current date using if statements before checking the time. Your formatting was slightly off, as digital.getHours() returns a whole number rather than those formatted strings.
I also added a setInterval to update the status every minute, in case the page is left open for prolonged time.
Here is the fiddle: http://jsfiddle.net/u6bwJ/1/
EDIT: Fixed a few bugs (namely typos). I also see you need localization for this. I made some changes to the top of the code which adjust for timezone, so it's always displaying information based on local time. There is one caveat though, and that is that it is currently hardcoded to include daylight savings. This means it will be inaccurate once DST switches.
Line 10:
utc1Time=new Date(localTime.getTime() + (localTime.getTimezoneOffset() + 120) * 60000);
That + 120 is adding 2 hours after converting client time to UTC time, which makes it UTC+1 and then adds the DST offset. You will need to add some way to check if DST is in effect, something along the lines of
utc1Time.toString().match(/daylight/i)
but I will leave that to you, as this is probably enough of a framework for you to build upon.
Hope this helped :D

Related

Jquery script doesn't work so I have to fix the code

I would like to disable some fields on a select box, depending on the date and time. I have a WooCommerce website. On my checkout page, I have a select box within a list of specific dates and times when I deliver my product. I would like to prevent visitors from scheduling a delivery for the same day that they place an order. My delivery days are Wed 10:00 - 12:00, Wed 16:00 - 18:00, Sat 10:00 - 12:00, and Sat 12:00 - 14:00.
If a visitor goes to checkout on Wed, I want prevent them from choosing a Wed delivery date (by disabling Wed on the select box), so they can choose only between Sat 10:00 - 12:00 and Sat 12:00 - 14:00. The same is true for Sat.
I am trying to write some jQuery code, but it isn't working. Please, could someone help me to fix this code?
Checkout page link
jQuery(document).ready(function() {
var dmain = new Date(); // for now
dayis = dmain.getDay();
houris = dmain.getHours();
if(dayis == 3 && houris >= 8){
jQuery("#billing_woocmm9 option[value='mercoledì 10:00 - 12:00']").hide();
jQuery("#billing_woocmm9 option[value='mercoledì 16:00 - 18:00']").hide();
}
if(dayis == 6 && houris >= 7){
jQuery("#billing_woocmm9 option[value='sabato 10:00 - 12.00']").hide();
jQuery("#billing_woocmm9 option[value='sabato 12:00 - 14:00']").hide();
}
Your help will be really appreciated. Thank you so much!
As that comment says, there is a missing } at the end. Also, while we're at it, "let" is a better statement than "var" in this situation because "var" will declare the variable globally, whereas "let" will restrict it to this small scope. Also, the variable names shouldn't really be suffixed by "is" at the end because the == operator does that for you. Also, I don't think the hide() method can be used on "option" elements, so you should use the remove() method instead. Also, you might want to check that those values for your options are actually what are used by the site. Typically, option values are a condensed, non-verbose, abbreviation for what is selected, so that could also be the problem. Anyway, here's what might work for you:
jQuery(document).ready(function() {
let now = new Date();
let day = now.getDay();
if (day == 3) {
jQuery("#billing_woocmm9 option[value^='mercoledì']").remove();
}
else if (day == 6) {
jQuery("#billing_woocmm9 option[value^='sabato']").remove();
}
}
And here is an alternative method that uses dictionary lookups to avoid a little bit of code repetition:
jQuery(document).ready(function() {
let now = new Date();
let day = now.getDay();
let day_value_prefixes = {
3: "mercoled",
6: "sabato",
};
if (day_value_prefixes.hasOwnProperty(day)) {
jQuery("#billing_woocmm9 option[value^='"+day_value_prefixes[day]+"']").remove();
}
}
Note that in both of these methods, I used "value^=". The ^= operator here selects values that start with the string, so that we can ignore the ending of the string with all the spaces. Generally, I like to avoid selecting based on weird characters like that to avoid any problems that might arise from unnoticed double spaces or anything. Also, along those same lines, I generally don't like to use non-ascii characters like ì internally, in non-user-facing situations, in case there is some weird encoding problem that causes them not to match with selectors or if there is some very similar-looking but technically different character that I would get them confused with.
If you are still having problems, it would be helpful if you would post the relevant html. It could be that your selector is off somehow - maybe you are using the wrong id for your select tag or something. You might want to also check that your script is actually being loaded onto the page.

Correctly treating DST shift with momentJS

I've came across something that I thought it was right, but now taking a closer look something is clearly wrong.
I'm on a project of a pill reminder app where someone can set notifications to remind him/her of taking pills in the correct time. There're medicines which a person can take for the rest of his life. And in that case I don't set alerts for years, I set for 3 months max and, when he takes one and mark it as done, I set another alert for 3 months later starting on that date/time.
This app will be released only in Brazil and we have Daylight Saving Time here. When it shifts to DST time the clocks must be adjusted to -1 hour after midnight, when going off DST it gains 1 hour.
For this project I'm using Firebase, Ionic 2, the LocalNotification Plugin and Moment JS.
I have to make a story of the user because other user can see if he's taking it correctly, so I use Moment JS to manipulate the datetime and save the notification and create a node for that user in firebase with UNIX time.
LET'S FINALLY GO TO THE PROBLEM.
When saving a date I check if this date is DST, if it is I add +3 hours to it, if it's not I add +2. I need to add this because when I wrap the isoString in the Moment() function it gives me -3 hours or -2 hours (Haven't searched for this, but I think Moment uses USA time).
This works fine if I'm saving dates inside DST times if I'm in DST time, if in some case I'm not on DST and save a notification for a DST time day it saves with +2 hours.
AN EXAMPLE
The DST time will shift to in DST on October 15. If I need to save 30 notifications, one per day everyday as 12AM, starting at October 1 up to October 30. From day 1 to day 15 the dates will be right, from day 16 to 30 they'll be with +2 hours.
Here's the basic code I use:
// THIS'LL SET MY DATEPICKER TO THE DATE/HOUR I'M IN.
minDate: any = Moment().isDST ? Moment().subtract(3, 'h').toDate().toISOString() : Moment().subtract(2, 'h').toDate().toISOString();
// THIS'LL CONVERT THE SELECTED DATE TO A UNIX TIME IN WICH I'LL USE TO SAVE THE NOTIFICATION AND THE MEDICATION DATA ON FIREBASE
unixConverted = Moment(this.minDate).isDST ? Moment(this.minDate).add(3, 'h').unix() : Moment(this.minDate).add(2, 'h').unix();
What is strange is that using Moment().unix() alone it give me the right time I'm in, if I use Moment(this.minDate).unix() it gives me -2 or -3 hours of the hour I selected.
So if it's in DST (in which I've set my clock to -1 hour) I add 3, if not I add 2.
So how is the proper way to manipulate this DST shift?
Is there a better way to do this than using DST?
Am I right using this logic or is this much more complex than what I think?
Ok so i've found a better way without using .isDST() method.
Simple use Moment().add(Moment().utcOffset(), 'm'), this'll get the current moment time and add the offset in minutes.
The .add() and .subract() methods makes Moment return the UTC time.
The utcOffset() returns a positive or negative number of minutes (representing hours) from UTC, like -60 or 180. So i'll get the correct respecting the time shift.
Worked like a charm for me.

How to do total 24 hrs validation maintaning 12 hrs format using javascript?

In my web app Form i ve two fields called startTime,closeTime which are repeated in every row of the table.now i ve to validate for 24hrs(1440 mins) from startTime of the first row to closeTime of the last row.but user enters time in 12 hr format means if startTime of the first row is 08:00 am then i ve to check upto 08:00 am of next day(every thing i am converting into minutes).i tried in several ways but unable to caliculations missing in am to pm/pm to am please help me.following is my code (onclick of first column of every row it ll be called)
var timeArray=[""],timeArray1=[""],timeNoon,closeNoon,temp=0,sumTime=0;
function checkTime(){
var startTime,closeTime;
if(rowIndex!=0){//rowIndex is current row index
startTime=document.getElementById("logSheetDataTable").rows[rowIndex-1].cells[j].childNodes[0].tBodies[0].rows[0].cells[1].childNodes[0].value;
closeTime = document.getElementById("logSheetDataTable").rows[rowIndex-1].cells[j].childNodes[0].tBodies[0].rows[1].cells[1].childNodes[0].value;
timeNoon=startTime.substring(6);//to get am or pm
startTime = startTime.substring(0,5);//to get tome 08:00
timeArray = startTime.split(":");
closeNoon=closeTime.substring(6);//to get am or pm
closeTime1=closeTime.substring(0,5);
timeArray1=closeTime1.split(":");
if(timeNoon.toLowerCase()=="pm"){
startMin=parseInt((timeArray[0]*60))+parseInt(timeArray[1])+720;
}else if(timeNoon.toLowerCase()=="am"){
startMin=parseInt((timeArray[0]*60))+parseInt(timeArray[1]);
}
if(closeNoon.toLowerCase()=="pm"){
endMin=parseInt((timeArray1[0]*60))+parseInt(timeArray1[1]+720);
}else if(closeNoon.toLowerCase()=="am"){
endMin=parseInt((timeArray1[0]*60))+parseInt(timeArray1[1]);
}
if(startMin<endMin){
temp=endMin-startMin;
}else if(startMin>endMin){
temp=(1440-startMin)+endMin;
}
sumTime=sumTime+temp;
alert("sum: "+sumTime);
}
for sumTime i ve to check for 1440 mins.
It sounds like you've got a table that looks something like this:
START END
08:00 am 10:00 am
10:00 am 03:00 pm
03:00 pm 08:00 am
And you're saying that you want to validate that 24 hours has passed from the START in the first row and the END in the last row. If that's all you want to do what's all the rest of your code for?
The calculation you've got in your code looks like you're adding up the time between each START and END on the row, then summing these, presumably to check if you've got to 24 hours. You're not checking the first START + last END, so is this valid (three lots of 8 hours==24)?
START END
01:00 am 09:00 am
01:00 am 09:00 am
01:00 am 09:00 am
When you're splitting out the string, you're always taking the first 5 characters and assuming that they are of the form HH:MM. Is this always correct (you're never going to encounter a time where for example the 0 prefix is missing, so you have 8:00am? Are you sure that there will always be exactly 1 space after the time, before the am/pm? Are you sure there is nothing after the am/pm? All of these will effect whether or not your string parsing works correctly...
Some of the ways that you're extracting numbers look a bit dodgy to me. For example:
startMin=parseInt((timeArray[0]*60))+parseInt(timeArray[1])+720;
Look carefully at the brackets. You calling parseInt on the result of (timeArray[0]*60). Presumably this should be calling it, before you try to do mathematical operations:
startMin=(parseInt(timeArray[0])*60)+parseInt(timeArray[1])+720;
This is a common problem with a lot of your calls to parseInt which may be causing some unexpected issues...
Now, looking at the calculation for the time difference between each start and end on a single row...
If the time is pm, add twelve hours (720 minutes) to convert it to 24 hours clock. You seem to be trying to do this, you're also converting it into minutes at the same time.
Now, you have three scenarios.
START == END - This will either be 0 or 24 hours, currently you don't seem to cater for this.
START > END - The day has rolled over between the START time and END time. So, you need to calculate the (time to the end of the day) + END time. So in minutes, you'd have 1440 - startMin + endMin. You seem to be doing this correctly...
END > START - End is later than start, so you just need the difference: endMin - startMin, again you seem to be doing this correctly.
So, there must be something wrong with your code. I've had a bit of a fiddle and it turns our your problem is basically your bracketing. Because you've got them in the wrong place, your numbers are being used as strings sometimes + numbers others, so sometimes instead of addition, you get concatenation of the values which throws you way off...
The relevant fixes are:
if(timeNoon.toLowerCase()=="pm"){
startMin=(parseInt(timeArray[0])*60)+parseInt(timeArray[1])+720;
}else if(timeNoon.toLowerCase()=="am"){
startMin=(parseInt(timeArray[0])*60)+parseInt(timeArray[1]);
}
if(closeNoon.toLowerCase()=="pm"){
endMin=(parseInt(timeArray1[0])*60)+parseInt(timeArray1[1])+720;
}else if(closeNoon.toLowerCase()=="am"){
endMin=(parseInt(timeArray1[0])*60)+parseInt(timeArray1[1]);
}

JavaScript Addition Date Functions

I don't really know too much about core JavaScript, just a dot of jQuery. But I know jQuery is not necessary for what I need here:
I want to use the getdate function to find out the server's day of the week. Then add a bunch of clauses like:
if its Monday add 6 to the date and return the date in MM/DD/YYYY form.
if its Tuesday add 5 to the date and return the date in MM/DD/YYYY form.
if its Wednesday add 4 to the date and return the date in MM/DD/YYYY form.
and so on until Sunday when it will add 0.
So lets say todays Monday, it will return 1/8/2012
And in real dates today's Sunday so it will really return 1/1/2012
Then I just want to call a document.write function to write the MM/DD/YYYY it returns into my HTML document.
Can anybody help me? I can clarify if you need me to...
getDay() returns the day of the week, Sunday = 0, Monday = 1, etc, etc.
So say today was Monday getDay() would return 1, which means daysToAdd would be 5.
Once we know how many days we want to add we can create a new date and add those days. We do this by getting today in milliseconds and then adding the number of days (daysToAdd) in milliseconds.
We convert days to milliseconds by multiplying by 24*60*60*1000 which is the number of milliseconds in a day.
I add 1 to the month because JavaScript returns 0 based month, but for display purposes we want to format it so that January for example is 1 not zero.
function getEndOfWeek() {
var today = new Date();
var weekDay = today.getDay();
// if you want the week to start on Monday instead of Sunday uncomment the code below
//weekDay -= 1;
//if(weekDay < 0) {
// weekDay += 7;
//}
var daysToAdd = 6 - weekDay;
var newDate = new Date(today.getTime() + daysToAdd *24*60*60*1000);
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
var year = newDate.getFullYear();
var formatedDate = month + "/" + day + "/" + year;
return formatedDate;
}
You could implement in your code like so, JavaScript:
$(function() {
$("#TheDate").html(getEndOfWeek());
});
Your HTML would be something like this:
The week ends on <span id="TheDate"></span>.
You can find the jsFiddle here: jsFiddle
If you want to adjust the weekday so that you consider Monday the start of the week instead of Sunday you can do the following after you get the weekDay:
weekDay -= 1;
if(weekDay < 0) {
weekDay += 7;
}
var day = 1000*60*60*24
, nextSunday = new Date(+new Date() + day*(7-((0|(+new Date()/day)%7-3)||7)));
alert(
(101+nextSunday.getMonth()).toString().substr(1) + '/' +
(100+nextSunday.getDate()).toString().substr(1) + '/' +
nextSunday.getFullYear()
)
As fas as adding dates in JavaScipt my "DateExtensions" library does this well enough, I think. You can get it here:
http://depressedpress.com/javascript-extensions/dp_dateextensions/
Once refenced you can call "add()" as a method for any valid date and pass it any of many date parts (second, minutes, days, hours, etc). So assuming "curDate" is a valid JavaScript date object you can add 5 days like this:
newDate = curDate.add(5, "days");
Using a negative value will subtract:
newDate = curDate.add(-5, "days");
Once you get the date you want you can the use the library's dateFormat() method to display it like so:
curDate.dateFormat("MM/DD/YYYY");
There's full documentation at the link.
Integer Values for Day of Week
As for getting the integer value you want, it's actually easier that it looks (and you don't need an "if" just some math). The getDay() method of date returns the day of week with Sunday as "0" and Saturday as "6". So the week, from Sunday, would normally be:
0,1,2,3,4,5,6
First, you want to reverse that scale. That's easily done via subtraction by taking 7 (to total number of members of the set) from the value. This gives you this scale:
-7,-6,-5,-4,-3,-2,-1
We're getting closer. You want the first value to be zero as well. The simplest way (I think) to do this is to get the modulus (remainder) of the value by the total number of members. All this basically does is make "-7" a zero and leave the rest alone giving us this:
0,-6,-5,-4,-3,-2,-1
Almost done. Finally you don't want negative numbers so you need to use the Math.abs() method to eliminate the sign (get the absolute value) leaving us with our desired result:
0,6,5,4,3,2,1
For all the talk the acutual code is pretty compact:
Math.abs((cnt-7)%7)
Wrapping this into the original example gives us:
newDate = curDate.add(Math.abs((curDate.getDay()-7)%7), "days");
Server Vs Client
However take nnnnnn's comment to heart: in JavaScript the getDate() function gets the current date/time of the machine that it's running on - in the case of a web page that's the client, not the server.
If you actually meant the client time them you're set and done. If you really need the server time however that's annoying-to-impossible. If you own the server then it's actually not to hard to set up a rule that includes the current server in a cookie withing each fufilled request (you could then use my cookie library, also at the site above, to access the information!)
It's messier but depending on the server you might also be able to create an old-school server-side include that adds a bit of JavaScript to each page (preferably as a marked replace in the header) that hard-codes the date as a global variable.
You might also create a web service that returns the current server time but the client-overhead for that is insane compared to the data being delivered.
If the server's NOT yours (and you can't get the owner to provide the above) then the only real potential option is to do a straight http call and examine the HTTP "Date" header. Again however the overhead on this is immense compared to the return but it's really the only way. Any system like this would have to be very flexible however as any particular server might not return the date header or might not return it correctly.
Even if it does work understand that you might still not be getting the "server" time - or at least not the server you want. In a tiered architecture, for example an application server might render then page and hand it to a web server to return - you'd be getting the web server time, not the app server. Any number of appliances might also rewrite the headers (for example it's common to use dedicated SSL appliances to offload all the encryption work - these often re-write the headers themselves).
Sorry to get overly technical - JavaScript is definately one area where there's unfortunately rarely a "simple question". ;^)
Good Luck!

Substracting Dates in Javascript return a negative number

I am using the TimeTracker.js from link text to track Page Load times and put them in Google Analytics. Basically what it does is record a start time, and once the page loads it records a end time and then subtracts. These are recored using (new Date()).getTime().
Everything works fine except for instances where the time difference is between 0-100ms. Here I get a massive negative numbers such as -17,183,398,582. Does anyone know what is causing this? Is it got to do with the way Javascript is handling the date substraction or is it something to do with Analytics?
Any help much appreciated. Thanks
Just a guess, but that negative number sounds like it could be linked to Unix epoch time. Example:
var currentTime = new Date().getTime();
currentTime will hold a number such as 1289985468 which represents "GMT: Wed, 17 Nov 2010 09:17:48 GMT".
Perhaps there's a bug in that code you're using.

Categories

Resources