This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
I am trying to compare two dates which works properly on every device except the iPhone.Its giving wrong alert on iPhone.
jsfiddle
function play_time() {
var crntTime;
var today = new Date();
var formattedTime = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = yyyy + '-' + mm + '-' + dd;
var crntDatetime = `${today} ${formattedTime}`;
crntTime = new Date(crntDatetime).getTime();
var check = '2020-08-18 23:14:07';
var gameTime = new Date(check).getTime();
if (crntTime <= gameTime) {
alert('Play');
} else {
alert('Later');
}
}
<button onClick="play_time();"> show Time </button>
By using a space between the date and time in your check example, you're straying outside of the specification. That means that the implementation can use local time, or UTC, or refuse to parse it entirely.
Use the date time format in the specification which is basically what you have but with a T instead of space, or use the multi-argument Date constructor (for local time), or Date.UTC (passing the result into the Date constructor) for UTC. If parsing a string ideally always specify Z for UTC or a timezone offset. Date-only forms ("2020-08-19") are parsed in UTC but date-time forms ("2020-08-19T00:00:00") are parsed in local time — but, that changed more than once during the years 2015-2017 so it's a bit risky to rely on it.
In your situation, since you already have the information as separate variables, I would definitely use the multi-argument version of new Date or Date.UTC+new Date (depending on whether you want local or UTC).
Related
I built a script to put versions on some data my website fetches, but since users from all over the world use it Date.now() returns different results according to the timezone the user is in.
Is there an alternative to Date.now() or an option I overlooked that can standardize this?
Edit: This is what I need the date for:
function timeDB(){
let unix_timestamp = Date.now();
var date = new Date(unix_timestamp);
var hours = date.getHours();
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
if ( month <10){
year = year*10;
}
if ( day <10){
month = month*10;
}
if ( hours <10){
day = day*10;
}
var formattedTime = year + '' + month + '' + day + '' + hours;
return formattedTime;
}
This formated time will then be used as a version in my DB, so I need a universal timestamp.
Date.now returns an offset in milliseconds from 1970-01-01 UTC, it's unaffected by timezones or daylight saving, however it is affected by the accuracy of the host system's clock.
For a "universal" timestamp, you should use Universal Coordinated Time (UTC) values. You can build your own string using getUTC* methods such as getUTCFullYear, getUTCMonth, etc. or just use the string returned by toISOString and reformat the parts to suit.
If you just want YYYY MM DD HH then you can use a very simple function, the values are already zero padded strings so no need for the * 10 trick:
function timeDB(date = new Date()) {
return date.toISOString().split(/\D/).splice(0,4).join('');
}
console.log(timeDB());
There are many questions and answers already on how to format a date.
However, if you just want a unique value for versioning and only using current dates, then just using the value returned by Date.now should be sufficient. It's only 3 digits longer and you can trim it to 10 digits if you wish:
String(Date.now()).slice(0,10);
That effectively gives you a timestamp in seconds since the (fairly common) epoch of 1970-01-01 and is easily turned back into a date.
If your environment is properly configured to know its timezone (most browsers are) then all you need to do is add the timezone offset to your timestamp:
Date.now() + new Date().getTimezoneOffset() * 60 * 1000
I think you need UTC version of date and time so your code should be
function timeDB(){
let unix_timestamp = Date.now();
var date = new Date(unix_timestamp);
var hours = date.getUTCHours();
var year = date.getUTCFullYear();
var month = date.getUTCMonth()+1;
var day = date.getUTCDate();
if ( month <10){
year = year*10;
}
if ( day <10){
month = month*10;
}
if ( hours <10){
day = day*10;
}
var formattedTime = year + '' + month + '' + day + '' + hours;
return formattedTime;
}
This is will return the same values regardless the country is served from.
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 6 years ago.
I have pretty extensively researched this issue, and I've found some useful information, but I haven't been able to solve my problem. All I'm trying to do is parse a date and compare it to another date. Seems simple, right? Here is what I've tried:
function getCurrentDate() { //this function simply returns today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
return today;
}
$("#TxtDate").blur(function () {
var projectDueDate = Date.parse($("#lblDueDate").val()); //parses the project due date label to create a date variable
var itemDueDate = new Date($("#TxtDate").val()); //parses the value the user entered into the due date box to create a date variable
var actualProjectDueDate = new Date(projectDueDate);
if (Date.parse(document.getElementById('TxtDate').value) > getCurrentDate()) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtDate").val() = "";
}
});
The if statement isn't working in the TxtDate blur function. It is not showing the alert window, even though I am entering a date that precedes today's date. As you can see, I've tried some different things. Any suggestions?
Your function getCurrentDate is returning a string not a date object and you are comparing it with date object. So you need to parse the return value of getCurrentDate.
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse( getCurrentDate())) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtLeaveFrom").val() = "";
}
Date.parse() returns a date object while getCurrentDate() returns a string. Add the Date.parse() there too:
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse(getCurrentDate()))
This is how I am checking if a date is greater than the end-date of the first week.
Is there a better approach for this?
I also need to check the time along with the date.
function getTodayDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = dd + '/' + mm + '/' + yyyy;
return today;
}
function getFirstWeekDate() {
var today = new Date();
var dd = "7";
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
return dd + '/' + mm + '/' + yyyy;
}
var startDate = getTodayDate();
var endDate = getFirstWeekDate();
var regExp = /(\d{1,2})\/(\d{1,2})\/(\d{2,4})/;
if (parseInt(endDate.replace(regExp, "$3$2$1")) < parseInt(startDate.replace(regExp, "$3$2$1")))
{
}
There are several problems with your approach.
First, you're not actually checking the date of the weekend. You're just comparing it against the seventh day, so you're really checking if the date is one of the first six days of the month, and there are better ways to check that (such as calling getDate()).
Second, you are trying to treat the date as a number, but putting the most significant digits (the year) towards the end, which is backwards from how they should sort things. This works ok for your specific practice, since the month and year will always be the same in this instance, but if you're actually comparing any two dates it is wrong. If you're including time, it is especially wrong. In this case, you have two better solutions
Turn your dates into (tz consistent or tz free) ISO 8601 dates which will sort correctly. You can use the toISOString() method of a Date to do so.
Use a library such as Moment.js to do the date manipulation and comparison.
For example, if you had a Date object in now, you could create a Moment object representing this with
var nowMoment = moment(now);
which you could then use for various manipulations and comparisons. For example, if you wanted the end of the week for the month represented by nowMoment, you could do the following to get the start of the month and then the end of the first week
var weekEnd = moment(now).startOf('month').endOf('week');
You can then compare these. So if you wanted to know if the now variable is before the end of the first week, you can use something like
var isFirstWeek = nowMoment.isBefore( weekEnd );
The use case is that I am getting the date in millis (from epoch) through an ajax call, which now needs to be interpreted in the javascript. This corresponded to some point of time in UTC.
Now I need to display this date in PST, as that is the only relevant time zone for the users irrespective of where they are opening the page from.
Also, I need to show it in a different format like 'yyyy-mm-dd HH:mm' rather than the default Locale string.
Can someone please tell me, how I can do that.
Create a new date using the UNIX milliseconds value plus the offset to PST, then create your formatted string using getUTC series of calls.
Moment.js is a pretty nice library for this type of thing.
I believe the timezones are determined by the user's timezone setting when you use the new Date() function.
var myDateTime = 1312312732923;
var myDate = new Date(myDateTime);
var myFormattedDate = myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDay();
http://www.w3schools.com/jsref/jsref_obj_date.asp
JavaScript has now way to set the timezone that you want to display something in. I've used Flot for a library for charting and their suggested solution is to use the getUTC methods when displaying the dates. That means that your server code can't send the standard millis from epoch (since that would display GMT time), but a small adjustment on the server will make your dates display correctly on the client.
To read about the problem, see http://flot.googlecode.com/svn/trunk/API.txt, and look for the heading "Time series data"
Use the Date object: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Javascript's Date object works with milliseconds rather than seconds, so you'll have to multiply a UNIX timestamp by 1000:
var myDate = new Date(unix_timestamp * 1000);
Then, you can use the local-specific Date object to do whatever you'd like:
var output = myDate .getHours() + ':';
output += myDate .getMinutes() + ':';
output += myDate .getSeconds();
alert(output);
EDIT Ah, missed the part about using PST always, regardless of locale. unix_timesamp again is the epoch/UNIX timestamp you're getting from the server:
Try it here: http://jsfiddle.net/46PYZ/
// set to the UTC offset for the target timezone, PST = UTC - 8
var target_offset = -8;
// create a Date object
var myDate = new Date();
// add local time zone offset to get UTC time in msec
var utc_milliseconds = (unix_timesamp * 1000) + (myDate .getTimezoneOffset() * 60000);
// set the time using the calculated UTC timestamp
myDate.setTime(utc_milliseconds + (3600000 * target_offset));
// now build the yyyy-mm-dd HH:mm format
var output = myDate.getFullYear() + '-';
var month = myDate.getMonth() + 1;
output += (month < 10 ? '0' + month : month) + '-';
output += myDate.getDate() + ' ';
var hours = myDate.getHours() + 1;
output += (hours < 10 ? '0' + hours : hours) + ':';
var minutes= myDate.getMinutes() + 1;
output += (minutes< 10 ? '0' + minutes : minutes);
The W3C Geolocation API (among others) uses DOMTimeStamp for its time-of-fix.
This is "milliseconds since the start of the Unix Epoch".
What's the easiest way to convert this into a human readable format and adjust for the local timezone?
One version of the Date constructor takes the number of "milliseconds since the start of the Unix Epoch" as its first and only parameter.
Assuming your timestamp is in a variable called domTimeStamp, the following code will convert this timestamp to local time (assuming the user has the correct date and timezone set on her/his machine) and print a human-readable version of the date:
var d = new Date(domTimeStamp);
document.write(d.toLocaleString());
Other built-in date-formatting methods include:
Date.toDateString()
Date.toLocaleDateString()
Date.toLocaleTimeString()
Date.toString()
Date.toTimeString()
Date.toUTCString()
Assuming your requirement is to print the exact pattern of "HH:MM:SS MM-DD-YY", you could do something like this:
var d = new Date(domTimeStamp);
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds(),
month = d.getMonth() + 1,
day = d.getDate(),
year = d.getFullYear() % 100;
function pad(d) {
return (d < 10 ? "0" : "") + d;
}
var formattedDate = pad(hours) + ":"
+ pad(minutes) + ":"
+ pad(seconds) + " "
+ pad(month) + "-"
+ pad(day) + "-"
+ pad(year);
document.write(formattedDate);
var d = new Date(millisecondsSinceEpoch);
You can then format it however you like.
You may find datejs, particularly its toString formatting, helpful.