Compare a date in string format with todays date - javascript

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");}

Related

Comparing Dates in NodeJS IF Statement

I am using nodejs/javascript and trying to compare two dates to each other in order to apply a specific style if the date is before the set date.
Here is what I have:
var d = new Date();
var date = d.getMonth()+1+'/'+d.getDate()+'/'+(d.getFullYear().toString().substr(-2)-1);
var da = new Date('1/4/18');
var da_test = da.getMonth()+1+'/'+da.getDate()+'/'+(da.getFullYear().toString().substr(-2));
if(da_test < date) {
// do something
}
date_test is currently returning the date from a year ago today, 1/23/18. I have set the other date that it will compare itself to, to 1/4/18. While this should be true, for some reason it is not whenever the IF statement runs. However, if I change the date to something like 1/2/18, then it returns true. How is that the case and how can it be changed so it will return true if it is any date before 1/23/18?
You can compare those two dates like this:
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2 < d1) ...
In your code example you are comparing two Strings
You can compare the milliseconds since epoch (the number of milliseconds since 1 January 1970 00:00:00)
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.getTime() < d1.getTime()) {
}
You can also compare ISO date strings
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.toISOString() < d1.toISOString()) {
}

date object doesn't seem to be accurate when compared to today's date

I have this function that takes todays date and compares it to two weeks out. when it's less than or equal to the current date, it's supposed to add a class. However if it's today's date, it's not working. Otherwise it's working fine. Any ideas? Thanks
publicMethods.campaignEndDateAlert = function (dateString) {
if (!dateString) {
return dateString
};
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14);
var inputDate = new Date(dateString);
// This is the part that doesn't seem to work - the first part of this if statement
if ((inputDate >= currentDate) && (inputDate <= twoWeeks)) {
dateString = '<span class="red">' + ax.Utils.RFCFormat(dateString, { excludeTime: true }) + '</span>';
} else {
dateString = ax.Utils.RFCFormat(dateString, { excludeTime: true })
};
return dateString;
};
Due to the information you provided:
You said that if it is today's date it doesn't work as expected. That is because new Date() will provide a date object with today's date and time. IF the value of dateString is something like "07-13-2017" without the time, you will need to strip the time out of the currentDate object if you expect inputDate >= currentDate to be true. Try using currentDate.setHours(0, 0, 0, 0); before comparing to inputDate.

How to check if one DateTime is later than another in javascript

Through the form i am getting two values like
Start datetime = '01/12/2013 12:00:00 AM' and
End datetime = '02/12/2013 12:00:00 AM'.
How I can validate the start datetime must be less than end datetime in javascript?
Asuming you received a date in Javascript Date format you need Date.parse() function or compare by comparison operators. It will return the milliseconds that have passed since 01/01/1970 00:00
Somehow like this:
if(Date.parse(datetimeStart) < Date.parse(datetimeEnd)){
//start is less than End
}else{
//end is less than start
}
Here is a Fiddle
its really simple in javascript
var startTime = new Date('01/12/2013 12:00:00 AM');
var endTime = new Date('02/12/2013 12:00:00 AM');
and then all you need to do is compare
if( startTime < endTime){
alert("start time is lesser");
}
More on this here
Try this following code:
function dateCheck() {
var fDate = new Date("26/05/2013");
var lDate = new Date("24/05/2013");
if(fDate <= lDate) {
alert("true");
return true;
}
alert("false");
return false;
}
//StartDate & EndDate two dates
if (StartDate < EndDate)
// code
if you just want the dates, and not the time
if (StartDate.Date < EndDate.Date)
// code
If you want to compare only dates then this will work.
var dt1 = new Date('12/31/2013');
var dt2 = new Date('12/31/2014');
var dt1obj = Date.parse(dt1);
var dt2obj = Date.parse(dt2);
if(dt2obj <= dt1obj){
//your code here...
}else{
//your code here...
}
var record_day1=fromDate.split("/");
var sum1=record_day1[1]+'/'+record_day1[0]+'/'+record_day1[2];
var record_day2=toDate.split("/");
var sum2=record_day2[1]+'/'+record_day2[0]+'/'+record_day2[2];
var record1 = new Date(sum1);
var record2 = new Date(sum2);
if(record2 < record1)
{
alert("End date must be greater than start date");
return false;
}
Here we are splitting the date and then combining it for comparing it hope it will work thanks.....:)
use the date object
Date1 = new Date('01/12/2013 12:00:00 AM');
Date2 = new Date('02/12/2013 12:00:00 AM');
Date1-Date2//in millisecond
You can use Date.parse as following
if (Date.parse(datetimeStart) < Date.parse(datetimeEnd)) {} else {}

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
}

Compare two dates in 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.

Categories