I feel this is a simple question, but there are several factors in play here which make it a bit more complex than it would seem.
For a site, we need to change a page weekly (with javascript/jQuery, no PHP or anything), with the transition being sunday 00:00 AM (from sunday to monday). It is important this happens on that minute/hour, due to page content being relevant for past and next weeks (actions, discounts, product advertisements etc.).
I searched a lot, tried several scripts, and i eventually ended up with this script:
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
};
var today = new Date();
var currentWeekNumber = today.getWeek();
//Returns weeknumber, content is adjusted through if(weeknumber == 35){etc.}
Now this seems to do what i want it to do, but when we tested it last sunday it seemed to initiate (at least) 3 hours too early as far as we could see (oddly enough not too many testers at sundaynight!).
Could anyone help me get underway with a proper script?
Something that adds to my struggle is timezones. I live in Amsterdam (GMT+2), and the visitors will be in the same timezone (Netherlands, the site is not aimed at people outside this zone).
Another thing that adds to the complexity for me, is that i am unable to test this more than 1 time a week. So any help with that would already be handy.
Summary: I need to change webcontent every week at sunday->monday 00:00 AM and a script to help me do that.
Something like this?
var d = new Date()
var n = d.getDay() //returns 0-6 for Sunday to Saturday
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
var time = hours+':'+minutes+':'+seconds;
if(n==1 && time=='00:00:00'){
//do something
}
Related
I'm developing a website where registrations for a particular event will open on a certain date (say, January 1, 2019) and will close on another date (say, January 10, 2019). I'm using JavaScript to redirect users to the relevant pages if they try to access it on before the 1st or after the 10 of January.
My code so far:
var d = new Date();
var startDate = new Date(2019, 0, 1, 8);
var endDate = new Date(2019, 0, 10, 23, 59);
if(endDate-d<0) // Past expiration date
window.location = "register-closed.html";
else if(startDate-d > 0) // Before starting
window.location = "register-unavailable.html";
The main problem as you might have guessed is that this code takes the local date and time from the user; if I set the date on my device as 2nd January, 2019, I'm able to access the actual register page, even though it's May right now.
I feel this would be a common problem for many, but I've been unable to find any solution to this. How do I get the REAL date and time for my country (India) instead of the device time?
TL;DR
How do I get the actual date and time for a country (in my case, INDIA) using JavaScript? If I can't use vanilla JS, is there some other method to do so?
PS: If you have any solutions that can only be bypassed using methods more complicated than changing your device time, I'll readily accept them. This whole website is just for a high school event, so I don't expect any skilled hackers to spend their time on this :)
This code will get the date (as in the 30th), month, and year. This uses the new Date(); variable type. It has several uses, and you can get the output in whatever order using something like new Date(year, month, day, hours, minutes, seconds, milliseconds). That would output something like Wed May 22 2019 10:46:32 GMT-0400 (Eastern Daylight Time).
var todaysDate = new Date();
var date = todaysDate.getDate();
var month = todaysDate.getMonth();
var year = todaysDate.getFullYear();
if(date === 10 || month === 0 || year === 2019){
//January is 0 because counting starts at 0
...
}
https://www.w3schools.com/jsref/jsref_obj_date.asp
you should take a look to this topic as it seems to answer to your problem using only vanilla JS. Hope it helps :)
I have some JavaScript that pulls dates out of two fields on my web page:
var StartDate = document.getElementById('StartDate');
var EndDate = document.getElementById('EndDate');
When I get these two dates I have the following snippet of code that performs the date subtraction:
var day = 1000*60*60*24;
var d1 = new Date(StartDate.value);
var d2 = new Date(EndDate.value);
var difference = (Math.ceil((d2.getTime() - d1.getTime()) / day))
Now is when the problem comes in. Say that my two dates are as such:
StartDate = 2013-05-01
EndDate = 2013-06-30
Using the calculator we get:
1372564800000 - 1367380800000 = 5184000000
5184000000 / 86400000 = 60 days
However, next let's use the following dates:
StartDate = 2013-10-01
EndDate = 2013-11-30
Again, using the calculator we get:
1385787600000 - 1380600000000 = 5187600000
5187600000 / 86400000 = 60.04166666666667 days
I'm just not sure how this is possible, I am using two identical date ranges. Both start days start on the first of a month with 31 days, and both end days end on the last day of a month with 30 days. When I put these date ranges into a MS Excel workbook I get the correct number of days:
=(EndCell-StartCell)
And I again get the 60 days for both sets of date ranges.
This seems to only happen when I cross into November of 2013. It doesn't happen when I cross into November of 2014, and I cannot find any other times when this happens. I know 2013 is gone, but my application will deal heavily with 2013 dates. Does anybody know of a reason why/how this is happening? Does anybody know of a better way to do date subtraction with JavaScript that will not cause this issue?
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!
I have a flash site that I need to put in a page a list of the food menu, in this site will have 6 menu's of food, and each menu is for one week, in first week will have the first menu until the last week that is the six will have the sixt menu, than it will return in the beginning and starts again. Basically the menu's will make a loop in the weekends. I was told me that its better to do in Javascript since it looks like in ActionScript isn't possible, so I think i'll export the info of a html page to a swf.
My question is how can I control in Javascript a event of a object whit my time zone and days, can someone give me a idea or guide me to a tutorial in the web that explains what im looking for?
JavaScript has a Date object that returns the time based on the user's clock, so the timezone will already be set to their local time.
Docs for the Date object: http://www.w3schools.com/jsref/jsref_obj_date.asp
Some noteworthy methods of the Date object:
getTimezoneOffset() - Returns the time difference between GMT and local time, in minutes
getTime() - Returns the number of milliseconds since midnight Jan 1, 1970
If you want to show/hide content based on what week it is in the year, you can setup a getWeek() method:
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
Usage:
var today = new Date();
var weekno = today.getWeek();
I have no acess to php. Is this possible w/ jquery?
Here is an example.
lets say the business opens at 11:00am and closes at 7:00 and the would like for a live chat image to say 'we're online!' but when they're closed they want the image to say 'we're offline'.
Does this help? If anyone has a solution to this please help. thanks.
You could get the client date using the Date object and datejs to simplify date manipulations like parsing, ...
Here's how to compensate for other timezones using Central Standard Time as the server's timezone:
http://jsfiddle.net/pxfunc/AcFhg/2/
javascript/jQuery:
// Translate your hours to UTC, example here is using Central Standard Time (-0500 UTC)
// Opening hour in UTC is 16, Closing hour is 0 the next day
var d = new Date(),
open = new Date(),
closed = new Date();
// Statically set UTC date for open
open.setUTCHours(16); // Open time at 11:00 am CST which is 16:00 UTC
open.setUTCMinutes(0);
open.setUTCSeconds(0);
open.setUTCMilliseconds(0);
// Statically Set UTC date for closing
closed.setUTCDate(d.getUTCDate()+1); // UTC time rotates back to 0 so we add a day
closed.setUTCHours(0); // Closing time at 7:00 pm CST which is 00:00 UTC (so we need to add a day)
closed.setUTCMinutes(0);
closed.setUTCSeconds(0);
closed.setUTCMilliseconds(0);
// Debugging
console.log("user's date:" + d);
console.log("store open time in user's timezone:" + open);
console.log("store close time in user's timezone:" + closed);
console.log(d > open); // user's time is greater than opening time
console.log(d < closed); // is user's time less than closing time (you don't have to go home...)
// Test for store open?
if (d > open && d < closed) {
setOpenStatus(true);
}
else {
setOpenStatus(false);
}
function setOpenStatus(isOpen) {
$('#open').toggle(isOpen);
$('#closed').toggle(!isOpen);
}
Note: it would be really difficult to fully compensate for the various daylight savings changes around the world but this will work for most cases
As multiple people have pointed out, anything you do on the client machine will be based on the client time rather than your actual business time.
Why don't you put an image on the page, don't worry about changing anything on the page, and just change the image on your server when your business opens or closes?
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if ((h > 18) || (h < 11)) {
$(img).src('closed.jpg');
}
<script type="text/javascript">
<!--
var objDate = new Date();
var hours = objDate.getHours();
var imgsrc = (hours > 11 && hours < 19) ? 'open.jpg' : 'close.jpg';
document.write('<img src="'+imgsrc+'" />');
//-->
</script>
hopefully following can help you a bit
http://www.w3schools.com/JS/js_if_else.asp