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 :)
Related
Not looking for solutions, just want to know why I get those results and get a better understanding of javascript.
I'm calculating dates and date strings for today through 3 days ago. If I zero out time for today, everything works just fine. If I don't (and maybe also it's close to midnight UTC) yesterday is a month ago, other previous day calculations work as expected.
Screenshot:
Code run in the console at about 5:30p eastern which is 11:30p UTC
Here's the code so you can run it yourself.
Zero out time and yesterday is yesterday:
let today = new Date();
today.setUTCHours(0,0,0); // remove time, otherwise yesterday if based off of today could be a month ago.
let todays_date_string = today.toISOString().slice(0, 10);
let yesterday = new Date(todays_date_string);
yesterday.setDate(today.getDate() - 1);
let yesterdays_date_string = yesterday.toISOString().slice(0, 10);
let two_days_ago = new Date(yesterdays_date_string);
two_days_ago.setDate(two_days_ago.getDate() - 1);
let two_days_ago_date_string = two_days_ago.toISOString().slice(0, 10);
let three_days_ago = new Date(two_days_ago_date_string);
three_days_ago.setDate(three_days_ago.getDate() - 1);
let three_days_ago_date_string = three_days_ago.toISOString().slice(0, 10);
console.log({today, today_s: today.toISOString(), todays_date_string, yesterdays_date_string, two_days_ago_date_string, three_days_ago_date_string});
Don't zero out time and yesterday is a month ago:
let today = new Date();
//today.setUTCHours(0,0,0); // remove time, otherwise yesterday if based off of today could be a month ago.
let todays_date_string = today.toISOString().slice(0, 10);
let yesterday = new Date(todays_date_string);
yesterday.setDate(today.getDate() - 1);
let yesterdays_date_string = yesterday.toISOString().slice(0, 10);
let two_days_ago = new Date(yesterdays_date_string);
two_days_ago.setDate(two_days_ago.getDate() - 1);
let two_days_ago_date_string = two_days_ago.toISOString().slice(0, 10);
let three_days_ago = new Date(two_days_ago_date_string);
three_days_ago.setDate(three_days_ago.getDate() - 1);
let three_days_ago_date_string = three_days_ago.toISOString().slice(0, 10);
console.log({today, today_s: today.toISOString(), todays_date_string, yesterdays_date_string, two_days_ago_date_string, three_days_ago_date_string});
Also note that I'm using today to calculate yesterday's date rather than the newly created yesterday based off today's date string which could be a contributing factor. But I wouldn't think that would affect calculating yesterday and certainly not to that degree.
Is there an explanation for this?
The key point is this: The setDate() method changes the day of the month of a given Date instance, based on local time.
Let's walk through some code.
const date = new Date('2023-02-01T22:34:47.458Z');
const todayDateString = date.toISOString().slice(0, 10); // 2023-02-01
const todayDateDate = new Date(todayDateString);
The value of todayDateDate.toISOString() is 2023-02-01T00:00:00.000Z
The value of date.getDate() is 1.
The value of todayDateDate.toString() is Tue Jan 31 2023 19:00:00 GMT-0500 (Eastern Standard Time) (this will vary depending on your time zone).
The local date is January 31!
If you setDate(0), it gives you the last day of the previous month, based on local time. Since the local time is in January, this means December 31 in local time, and will be January 1 UTC.
The exact results depend on your local time zone.
When you construct the new date that doesn't explicitly specify a time zone, e.g. new Date('2023-02-01'), the date is interpreted in your local time zone.
But when you stringify it via toISOString() you get the date in the UTC time zone, which could be a different day (the other side of midnight).
Consider:
// February 1 in UTC+05:00
const d1 = new Date('2023-02-01T01:00:00+05:00')
// is still January 31 in UTC
console.log(d1.toISOString()); // 2023-01-31T20:00:00.000Z
So if
your timezone offset means it's still yesterday in UTC, and
yesterday was still January 31 instead of February 1, then
setDate(1) makes it January 1: a month ago.
So there is a column that has the date with the hour and i was trying to create a variable date with the same date, month, year and hour to be able to compare it wiht that date but this didn't work with me so I thought I would do that by creating the same date but when i compare i won't consider the hour but im facing some difficulties.
anyone of the two solutions would be great
I wrote many other codes but none of them worked and that was the last one i wrote
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var date = month+'/'+day+'/'+year;
Logger.log(date);
Im using JavaScript in google app script.
Thank you!
From MDN
We have a first step to create an object date.
let today = new Date()
let birthday = new Date('December 17, 1995 03:24:00')
let birthday = new Date('1995-12-17T03:24:00')
let birthday = new Date(1995, 11, 17) // the month is 0-indexed
let birthday = new Date(1995, 11, 17, 3, 24, 0)
let birthday = new Date(628021800000) // passing epoch timestamp
You can create your Date object following the example above that fits you better. I also recommend giving a good look into this page.
For the second step...
From there, you can use Date.now(). As explained here, this will return "A Number representing the milliseconds elapsed since the UNIX epoch."
The third step is...
comparing both numbers. Which one is smaller will be an "earlier date" and vice-versa.
If some dates don't have time, I would consider it as midnight. Using the default Date format, that would be something like this.
yyyy-mm-ddThh:mm:ssZ
Ex:
2022-02-21T09:39:23Z
The Z at the end means UTC+0.
More about this on this link.
So, a date without time would be:
2022-02-21T00:00:00Z
I am defining a new Date object:
const date = new Date(2020, 09, 11);
The documentation says that the default time for the constructor is:
hours : 0,
minutes : 0,
seconds : 0... etc.
However, the result I get is:
const date = new Date(2020, 09, 11);
console.log(date);
2020-10-11T07:00:00.000Z
Why is the hour 7?
When I put the following into the console:
const date2 = new Date(2020, 09, 11, -7)
console.log(date2)
2020-10-11T00:00:00.000Z
I'm at a bit of a loss here.
That Z at the end stands for Zulu time = GMT. Since your difference is -7 I presume you are located at US Pacific Time. It's telling you that YOUR midnight is at 7am in the UK.
Javascript internally keeps track of time in UTC. The reason for this is to simplify global time synchronization with other users on the internet.
To display your local time do:
console.log(date.toLocaleString());
See also this answer to a related question: How to initialize a JavaScript Date to a particular time zone
The displayed time is correct, but in a different time zone. The standard timezone in most programming languages is called UTC (Universal Time Coordinated), GMT (Greenwich Mean Time) or Zulu Time. You can see it by the "Z" at the end of your time string.
According to the local setup on your computer you can use date.toLocaleString() --> But even here problems can arise, when your users did set their computer/browser time to a different timezone.
You can let your users set their timezones themselves and give these parameters to toLocaleString() according to https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Is it possible to get the next time it's 14:00 (for example) as a Date object in Javascript using Datejs?
The documentation doesn't seem to show such an example and trying next 14:00 doesn't really seem to work.
You don't really need a library for this. You can create a Date object and if it's after 14:00, set the date to tomorrow, then set time to 14:00.
Edit
The original would allow any time from 14:00 to 14:59:59.999 as it only checked the hours. Updated so that any time from 14:00:00.001 to 23:59:59.999 is treated as after 14:00.
Also added Date.js version (the documentation for which is minimal — perhaps there's something better).
// Create a date for now and remember the time
var d = new Date();
var time = +d;
// Set the time to 14:00 and, if earlier than now, add a day
d.setHours(14,0,0,0);
if ( d < time) {
d.setDate(d.getDate() + 1);
}
document.write('Next 14:00: ' + d)
Here is the Date.js version. I couldn't find a CDN to include as a snippet.
// Equivalent using Date.js
var d = Date.present();
var t = +d;
d.set({hour:14});
if (d < t) {
d.addDays(1);
}
document.write('<br>' + d3);
Or, as one line:
Date.today().set({hour:14}).isBefore(Date.present())? Date.today().addDays(1).set({hour:14}) : Date.today().set({hour:14});
// Or
Date.today().set({hour:14}).addDays(Date.today().set({hour:14}).isBefore(Date.present())? 1:0);
I don't recommend the one liner versions; they're just there to show it can be done. They each create 3 date objects, whereas the other versions create only 1.
I do not know how to use Datejs, but here is a simple solution in pure JavaScript. Hopefully it helps a bit. This sample gets the current date and checks if it is already past 14:00, and if so, creates a Date object for 14:00 the next day. If it is not already past 14:00, it creates a Date object for 14:00 that day.
var currentDate = new Date();
if (currentDate.getHours() >= 14){
var newDate = new Date(currentDate.getYear(), currentDate.getMonth(), currentDate.getDate()+1, 14, 0, 0, 0);
}
else{
var newDate = new Date(currentDate.getYear(), currentDate.getMonth(), currentDate.getDate(), 14, 0, 0, 0);
}
I have been reading up on dates for days, seemingly going in circles here. I have a string in a DB that looks like this
2012,03,13,01,31,38
I want to create a js date object from it so...
new Date(2012,03,13,01,31,38);
Easy enough, right? But it comes back as
2012-04-13 05:31:38 +0000
So the month is off by 1 and the time is off by 4 hours (maybe DST or Timezone related???). I simply want a date that matches the one I provided. Its driving me nuts, dealing with these JS date objects.
How can I be sure the date object is the exact same date and time as the string suggests, I have no need for Timezone or DST changes, simply a date that matches a string.
More specifics regarding application:
My application for this need is for an iphone app I am developing in Titanium (which builds using JS). Basically, part of my app involves logging data and with that log I collect the device's current date and time. I save all of this information to a mySQL database. The field in the database looks like this format: "2012-02-16 00:12:32"
Here is where I start to run into problems. I am now offering the ability to edit the log, including the date and time it was logged. In order to use an iPhone "picker", I must convert the string above into a JS date object again. This usually screws things up for me. I essentially need to create a new date object with the date above, with timezone and dst being completely irrelevant, so that when I save back to the DB, its just the string above, modified as per the users request. It needs to not matter whether they are editing in pennsylvania or china, they are editing the same log date.
Sorry if this has been confusing. I am having a hard time figuring out this whole date stuff.
This depends on what your string is. If that string is UTC time, you need to parse it as that. If it's local time, you need to parse it as local time. You can make a helper method like this for that part:
function getDate(utc, year, month, day, hour, minute, second) {
if(utc) {
var utc = Date.UTC(year, month - 1, day, hour, minute, second);
return new Date(utc);
} else {
return new Date(year, month - 1, day, hour, minute, second);
}
}
Now, to parse your string, you can use this:
function fromString(utc, str) {
var parts = str.split(',');
var year = parts[0];
var month = parts[1];
var day = parts[2];
var hour = parts[3];
var minute = parts[4];
var second = parts[5];
return getDate(utc, year, month, day, hour, minute, second);
}
which you can use like this for your example:
var d = fromString(true, '2012,02,13,00,31,38'); // If UTC
var d = fromString(false, '2012,02,13,00,31,38'); // If local time
Here's a working jsFiddle that you can play with:
http://jsfiddle.net/rNqXW/
which also shows two ways to print the date (UTC or local). Hope this helps.
I had the same problem. There are two reasons for the weird time change:
Use new Date(Date.UTC(2012,03,13,01,31,38)) to avoid the time change.
Note that the month is zero based! Months go from 0 to 11 for this function.