Compare two dates in JavaScript - javascript

I am trying to compare two dates. I have this code which I thought would work a treat, but it didn't. For now I just want to alert with an error if the end date is less than the start date. The date style, yyyy-mm-dd, needs to be kept in this format for other events prior to this. What is wrong with this code?
startdate = "2009-11-01" ;
enddate = "2009-11-04" ;
var d1 = new Date(startdate)
var d2 = new Date(enddate)
if (d2 < d1) {
alert ("Error ! ) ;
}
document.cookie='st =' + startdate // set sytem cookie
document.cookie='en =' + enddate
window.location = self.location.href
window.opener.location.reload()
close()

Try using DateJS, an open-source JavaScript Date Library that can handle pretty much everything! The following example is working:
<script type="text/javascript" src="date.js"></script>
<script>
startdate = "2009-11-01";
enddate = "2009-11-04";
var d1 = Date.parse(startdate);
var d2 = Date.parse(enddate) ;
if (d1 < d2) {
alert ("Error!");
}
</script>

Someone finally uses ISO 8601 standard dates but then ...
You are using a nice international standard that JavaScript arguably should understand. But it doesn't.
The problem is that your dates are in ISO 8601 standard format which the built-in Date.parse() can't read.
JavaScript implements the older IETF dates from RFC 822/1123. One solution is to tweak them into the RFC-style, which you can see in RFC1123, and which look like dd month yyyy.
There is coding floating about that can scan the ISO format comprehensively, and now that you know to google for "iso standard date" you can get it. Over here I found this:
Date.prototype.setISO8601 = function (string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
}
js> t = new Date()
Sun Nov 01 2009 09:48:41 GMT-0800 (PST)
js> t.setISO8601("2009-11-01")
js> t
Sat Oct 31 2009 17:00:00 GMT-0700 (PDT)
The 11-01 is reinterpreted in my timezone, as long as all your dates get the same conversion then they should compare reasonably, otherwise you can add TZ info to your string or to the Date object.

The Date constructor cannot parse that format, and since you cannot change it, you should parse it manually, and pass the year, month and date parts to it, for example:
function compareDates(startDate, endDate) {
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
if (parseDate(endDate) < parseDate(startDate)) {
alert ("Error !");
}
}
Usage:
var startDate = "2009-11-01",
endDate = "2009-11-04";
compareDates(startDate, endDate);

var myDate=new Date();
myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}
source: http://www.w3schools.com/jS/js_obj_date.asp

If you only need to know if one date comes before the other, you could just use the Date object's getTime() method to compare their respective numbers of milliseconds since midnight Jan 1, 1970:
if( d2.getTime() < d1.getTime() )
{
alert("eeeek!");
}
--- Don't get mixed up and try to use getMilliseconds(), though :)
w3schools documentation on getTime()

USe this function for date comparison in javascript:
function fn_DateCompare(DateA, DateB) {
var a = new Date(DateA);
var b = new Date(DateB);
var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());
var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());
if (parseFloat(msDateA) < parseFloat(msDateB))
return -1; // less than
else if (parseFloat(msDateA) == parseFloat(msDateB))
return 0; // equal
else if (parseFloat(msDateA) > parseFloat(msDateB))
return 1; // greater than
else
return null; // error
}

I implemented the below code for a date comparison depending on current time - -
// get the current time from a hidden input which is being set by server time
// because client may have a wrong time
var ch = jQuery('#clockHours').val(); // e.g. 9,10 etc.
ch = parseInt(ch);
// get the today's date from a server value as well
var td = jQuery('#clockDate').val(); // may be => new Date(); e.g. 2014-05-15
td = Date.parse(td);
td.setHours(0, 0, 0, 0);
// get the input date
var inpdate = jQuery('#jform_in_date').val(); // may be => new Date(); e.g. 2014-05-15
inpdate = Date.parse(inpdate);
inpdate.setHours(0, 0, 0, 0);
// get yesterday's date. this is from server as well
yd = new Date();
yd.setFullYear(td.getFullYear(), td.getMonth(), td.getDate()-1);
yd.setHours(0, 0, 0, 0);
alert('today\'s date is: '+td.toString());
alert('yesterday\'s date is: '+yd.toString());
// if it is not 10 AM then dates from yesterday are valid
if(ch <= 9) {
if(inpdate.getTime() >= yd.getTime()) {
alert('Valid: dates from yesterday are allowed');
} else {
alert('Invalid: dates before yesterday are not allowed');
}
} else {
if(inpdate.getTime() >= td.getTime()) {
alert('Valid: dates from today are allowed');
} else {
alert('Invalid: dates before today are not allowed');
}
}
I hope this will help very clearly.

Related

Compare a date in string format with todays date

I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}

ISO date comparison in native javascript

i have muddling with date comparison in native javascript or jquery, can anybody point me out how i can quickly do the comparison with today's date in ISO-8601 format
Try This
var d1 = new Date('2013-08-02T10:09:08Z'), // 10:09 to
d2 = new Date('2013-08-02T10:20:08Z'); // 10:20 is 11 mins
//Get the difference
var diff = d2 - d1;
//Format this as desired.
if (diff > 60e3) console.log(
Math.floor(diff / 60e3), 'minutes ago'
);
else console.log(
Math.floor(diff / 1e3), 'seconds ago'
);
// 11 minutes ago
OR
alert((dateFromISO8601("2013-08-02T10:20:08Z") - dateFromISO8601("2013-08-02T10:09:08Z")) / 60000); //Response in Milisecnds so Divide by 60000 For Minutes
function dateFromISO8601(isostr) {
var parts = isostr.match(/\d+/g);
return new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
}
You can just do string comparison on two valid ISO8601 strings (i.e. new Date().toISOString()) and it'll work
"2021-07-02T21:50:01.926Z" > "2021-07-04T21:49:56.863Z" // false
You can compare two dates by using new Date() method in javascript. Here's is the code to compare two dates.
var date1 = "28/08/2008";
var date2 = "12/02/2014";
if(new Date(date1) > new Date(date2)){
alert("Date 1 is greater then Date 2");
}else{
alert("Date 2 is greater than Date 1");
}
Don't use the Date constructor to parse strings as the result is inconsistent across browsers. Manually parse the strings.
If you have an ISO 8601 format like 2014-08-05T01:28:48.909Z it's very easy to parse:
// Given an ISO 8601 string, return a date object
function parseISO(s) {
s = s.split(/\D/);
return new Date(Date.UTC(s[0],--s[1],s[2],s[3],s[4],s[5],s[6]));
}
Now you can compare the dates like:
var d0 = '2014-02-06T23:45:15.987Z';
var d1 = '2014-02-06T23:48:15.987Z';
if (parseISO(d0) < parseISO(d1)) {
// d0 is before d1
}

Convert yyyy-MM-ddTHH:mm:ss.fffZ to DateTime in JavaScript manually

I receive from a Webservice a String with a date in this format:
yyyy-MM-ddTHH:mm:ss.fffZ
I need to convert that String with JavaScript to a normal DateTime but without using the new Date('yyyy-MM-ddTHH:mm:ss.fffZ') because I'm using an old version of JavaScript that not support that conversion. I can split that string and get the:
Year
Month
Days
Time
but how to manipulate the time zone "fffZ" Any suggestions?
Here's a one liner from John Resig:
var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
I've founded the solution. Please check http://webcloud.se/log/JavaScript-and-ISO-8601/
Date.prototype.setISO8601 = function (string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
}
If you know it will be of this form (ISO 8601, wiki), you can parse with RegExp or string methods. Here is a RegExp example that lets you use timezone Z, +hh or +hh:mm.
var dateString = '2013-01-08T17:16:36.000Z';
var ISO_8601_re = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?(Z|[\+-]\d{2}(?::\d{2})?)$/,
m = dateString .match(ISO_8601_re);
var year = +m[1],
month = +m[2],
dayOfMonth = +m[3],
hour = +m[4],
minute = +m[5],
second = +m[6],
ms = +m[7], // +'' === 0
timezone = m[8];
if (timezone === 'Z') timezone = 0;
else timezone = timezone.split(':'), timezone = +(timezone[0][0]+'1') * (60*(+timezone[0].slice(1)) + (+timezone[1] || 0));
// timezone is now minutes
// your prefered way to construct
var myDate = new Date();
myDate.setUTCFullYear(year);
myDate.setUTCMonth(month - 1);
myDate.setUTCDate(dayOfMonth);
myDate.setUTCHours(hour);
myDate.setUTCMinutes(minute + timezone); // timezone offset set here, after hours
myDate.setUTCSeconds(second);
myDate.setUTCMilliseconds(ms);
console.log(myDate); // Tue Jan 08 2013 17:16:36 GMT+0000 (GMT Standard Time)
momentjs has the answer to this and many other date problems you might have.
While it isn't clear where and how you will user the needed date, neither the wanted format, I think momentjs can give you some of the needed tasks
I would add the module to my solution and use as (below is parse.com cloud code):
Parse.Cloud.define("momentFormat", function(request, response){
var message;
var date = momento('2013-01-08T17:16:36.000Z');
response.success("original format date: " + date.format("YYYY-MM-DDTHH:mm:ss.SSSZ") + " new format date: " + date.format("dddd, MMMM Do YYYY, h:mm:ss a"));
});
Output:
{"result":"original format date: 2013-01-08T17:16:36.000+00:00 new format date: Tuesday, January 8th 2013, 5:16:36 pm"}

Compare dates are not returning correct results in javascript

I am comparing two dates in javascript
function checkCurrentDate(expiryDate){
//var currentDateStr=expiryDate;
var currentDate = new Date();
var month = currentDate.getMonth() + 1;
var day = currentDate.getDate();
var year = currentDate.getFullYear();
currentDate = month + "/" + day + "/" + year;
var dArr = currentDate.split("/");
currentDate = dArr[0]+ "/" +dArr[1]+ "/" +dArr[2].substring(2);
var currentExpiryDateStr = expiryDate;
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
currently the dates are in "currentExpiryDateStr " is "11/10/12" and "currentDate" is "11/8/12" now in this condition "if(currentExpiryDateStr < currentDate)" is returning true and is entering in if condition but this condition should return false and should not enter in this if condition. It was working before but dont know why it is not working now.
The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
try this..
function checkCurrentDate(expiryDate){
var currentDate = new Date(); // now date object
var currentExpiryDateStr = new Date(expiryDate); //expiry date object
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
here is the fiddle:: http://jsfiddle.net/YFvAC/3/
var currentDate = Date.now();
if (expiryDate.getTime() < currentDate ) {
alert("Expiry date is earlier than the current date.");
return false;
}
The now() method returns the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now as a number.
The getTime() returns the Milliseconds since midnight January 1, 1970
You are comparing strings, you should be comparing date objects.
If the expriy date is '11/10/12' in the format month/day/year and that the year is a two digit year after 2000, you can convert that to a date using:
function mdyToDate(dateString) {
var b = dateString.split(/\D/);
return new Date('20' + b[2], --b[0], b[1]);
}
To test expiry, you can do something like:
function hasExpired(dateString) {
var expiryDate = mdyToDate(dateString);
var now = new Date();
return now > expiryDate;
}
So on 8-Nov-2012:
hasExpired('11/10/12'); // 10-Nov-2012 -- false
hasExpired('6/3/12'); // 03-Jun-2012 -- true
The hasExpired function can be replace with:
if (new Date() > mdyToDate(dateString)) {
// dateString has expired
}
Just add this 2 lines before your if condition
currentExpiryDateStr=Date.parse(currentExpiryDateStr);
currentDate=Date.parse(currentDate);

If month is not current month

We have a .NET web service which returns JSON, including a date in string format as follows: 2012-04-30T00:00:00+12:00.
In javascript, I want to exclude dates where the month is not the current month. Hence, with the above date, the month is 04 (April) and the current month is May (in New Zealand anyway). So, I want to ignore this record, e.g, in pseudocode:
if(vMonth == CurrentMonth){
dothis();
}
How can I do this?
EDIT: See Rob G's answer below for the solution that works in all browsers.
var dateOne = new Date("2012-04-30T00:00:00+12:00");​​​
var dateTwo = new Date();
if(dateOne.getMonth() == dateTwo.getMonth()) {
alert("equal");
}
Here's the jsfiddle:
http://jsfiddle.net/Mq5Tf/
More info on the date object:
MSDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
ES5: http://es5.github.com/#x15.9.2
var date = new Date();
var currentMonth = date.getMonth();
var yourMonth = 4;
if(yourMonth == currentMonth ){
/* Do this */
alert('Hello');
}
An alternative that doesn't depend on parsing the date string:
function checkMonth(ds) {
var now = new Date();
var m = now.getMonth() + 1;
return !!ds.match(now.getFullYear() + '-' + (m<10?'0':'') + m);
}
// on 2012-05-01
alert( checkMonth('2012-04-30T00:00:00+12:00') ); // false
alert( checkMonth('2012-05-01T00:00:00+12:00') ); // false
Edit
Note that checking the month number only works where the timezone offset should be ignored or is not significant. While 2012-04-30T00:00:00+12:00 is in April, 2012-04-30T14:00:00+12:00 will be 2am on 1 May local time.
// Means April 30, months are indexes in JS
var input = new Date(2012, 03, 30);​​​
// or use format new date("2012-04-30T00:00:00+12:00") suggested in other answer
var currentDate = new Date();
if(input.getFullYear() == currentDate.getFullYear() // if you care about year
&& input.getMonth() == currentDate.getMonth()) {
// act accordingly
}

Categories