I am trying to compare two dates but always it gives me opposite result.
I am trying to compare below dates
var tocompare=09/22/2017 and var insurenceexpiry=04/02/2018
I tried to compare as below.
console.log(insurenceexpiry > tocompare);
console.log(insurenceexpiry < tocompare);
which gives me false and true. As per my knowledge insurenceexpiry is greater and when i compare as insurenceexpiry > tocompare it should give me true but I am getting false. What I am doing wrong?
You have to convert it into dates using new Date(datestring).
Otherwise 9/22/2017 without quotes will do math operations
var tocompare=new Date("09/22/2017");
var insurenceexpiry=new Date("04/02/2018");
console.log(insurenceexpiry > tocompare);
console.log(insurenceexpiry < tocompare);
If you want to compare 2 dates as string directly, then use YYYY/MM/DD format, (you can use any separator apart from /, the main thing is YYYYMMDD)
Otherwise parse them as date (as per i--'s answer) and then compare, as a month or day can be bigger than another date, but that doesn't meant that it's actually a bigger date, so you cannot use mmddyyyy format for a simple string comparison to get which date is bigger.
Related
If I had an array of dates, is there a way I could match up another date by rounding up until one is matched?
For example, say I have an array of dates:
"2022-09-15"
"2022-10-10"
"2022-12-01"
And I have a date pulled from the application: "2022-09-29", I want the date to update itself by rounding up until the next upcoming date ("2022-10-10") is selected.
I am unsure how I would round up like I could in mathematics situations.
Assuming your dates are in order, you can iterate through your array starting at the beginning until you find the first date that is bigger than you date provided by the application. In JavaScript, your can do a direct comparison like this:
"2022-09-15" > "2022-10-10" // false
"2022-09-15" < "2022-10-10" // true
Note that this works because of the ordering of the year, month, and day that you have presented. If you wanted to do comparisons where you had day, month, year, you would want to create a Date JavaScript object and do the comparisons that way. You can read more about those here: Compare two dates with JavaScript
But for your use case, a simple loop could look like this:
for(let i = 0; i < array.length; i++) {
if(applicationDate < array[i])
return array[i]
}
You don't necessarily need to "round" the dates up. Incrementing the date and comparing it to every entry in the array until you find a match would take a relatively large amount of time and resources. I prefer a kind of "knock-out" approach to problems like this. Simply rule out everything it can't be until you're left with a single option. In this case, since you specifically need a date that comes after the input date, we can first rule out anything before the input date. We can then take this new list of dates (that we now know are all after the input date) and get the "smallest" one. This will effectively give you the date that is closest to the input date but still after it.
In your question you presented the dates as a list of strings. This isn't a huge deal because this can still be fairly easily accomplished, but the strings must be in a format that JavaScript recognizes as a date, otherwise all comparisons will result in false. Here is a list of the valid date formats.
I personally like to avoid depending on the order of arrays just because it can be hard to maintain and if/when it breaks, it's generally very hard to find that the issue is that the array is out of order (speaking from experience here). For this reason, the code examples provided here will be completely unreliant on the order of the array.
First, let's discuss a solution using Date objects. This is fairly straight forward. The only thing is that you would need to make sure the date being input is in a valid format as discussed previously. Keep in mind the input needs to be converted to a Date object (if it isn't already) because comparisons between date strings and Date objects always return false. To get only dates after the current date, we can use Array.prototype.filter(), and to get the "smallest" date afterwards we can use Math.min.apply() as explained in this Stack Overflow answer.
var dates = [
new Date("2022-09-15"),
new Date("2022-10-10"),
new Date("2022-12-01")
];
var inputDate = new Date("2022-09-29");
var datesAfter = dates.filter(x => x > inputDate);
var closestDate = new Date(Math.min.apply(null,datesAfter));
console.log(closestDate);
Now for date strings. The idea is largely the same as Date objects. The only difference really is that we can't use Math.min.apply() on date strings. We can however use Array.prototype.reduce() in order to compare all the dates, it's just a bit more involved.
var dates = [
"2022-09-15",
"2022-10-10",
"2022-12-01"
];
var inputDate = "2022-09-29";
var datesAfter = dates.filter(x => x > inputDate);
var closestDate = dates.reduce((a, b) => a > b ? a : b);
console.log(closestDate);
This is my data format:
"21/03/2019 19:18"
The problem i am facing is, when ever if i am dealing with date or time there is an issue with the month ( it has 03 instead of 3 ). I am using library called date-fns. And also i have tried with the help of javascript date objects without using library, but no luck still the month should not have zero in-front of it.
So, how to remove the "0" in-front of "3", and one more problem is how to do this conditionally , because when its Dec, i will be getting data as "21/12/2019 19:18". So, in this case , i should not remove "1" as its located in same position of "0" in previous scenario.
In other words, i want to remove "0" by checking if there is "1" presented in that position or index, if presented then remove else remove "0"
How to achieve this.
I tried the below code:
const d = new Date(2019,03,21)
But, its says legacy error. So when i removed "0" infront of "3" it works fine. Please help
I assume you get the data back as a string and you just want to remove leading zeros from the 2nd number only?
we can use .split to break up the string into parts, and then we can use parseInt to convert some string parts into numbers. that will turn the string "03" into the number 3
function removeleadingZerosFromDateString(str) {
//Break up the date string on the slashes and whitespace, so we have an array of all the parts
var parts = str.split(/\/|\s/);
console.log(parts);
//Assign each array item to a variable so we can see what is what
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parts[2];
var time = parts[3];
var meridian = parts[4];
return day+'/'+month+'/'+year+' '+time+' '+meridian;
}
var result = removeleadingZerosFromDateString("21/03/2019 19:18 PM");
console.log(result);
You said you were using date-fns, so I'll give an answer in that regard.
The current 1.x version doesn't support parsing strings in a custom format, but they are adding that to 2.x, and you can use the alpha release to try it today.
The syntax is:
var date = parse(dateString, formatString, baseDate, [options]);
See the documentation for the parse function in version 2.0.0-alpha.27.
In your case, it would be like this:
var date = parse("21/03/2019 19:18", "MM/dd/yyyy HH:mm", new Date());
Lastly, if you want to use a library for this but don't want to experiment with an alpha, you can either wait for Date-fns 2.0 to become final, or you can try Luxon or Moment - both of which already have this functionality (though Moment uses a slightly different token format "MM/DD/YYYY HH:mm").
I have 2 date:
start date
<input type="text" name="startdate" value="2016-04-08">
End date
<input type="text" name="enddate" value="2016-09-02">
but how to use javascript to validate days of the end date to not less than the days from start date.
like
startdate '08' = end date '02' and 'not ok'
or
startdate '08' = end date '08' and 'ok'
thankyou
If you only have to compare the days, all you have to do is checking if one value is equal to, or higher than the other.
You can accomplish this by getting both values, take the last part, and compare those. For example:
var date = '2016-04-08';
var day = date.split('-')[2];
split turns the string into an array: MDN
The last value is the day. If you want to compare it as a number, make sure to turn it into a number (or int): MDN
DEMO
If you want to compare the whole date, which makes more sense IMO, it's a bit more tricky. In that case you have to turn the values into proper JS Date objects. Once they are both Date objects, you can compare them.
For this you can also use the split part as above. Provide the three parts (year, month, day) to the Date object to create a valid date object.
DEMO
you can do like these,
function CheckSchedulingDates() {
var SD = document.getElementById('startdate').value;
var ED = document.getElementById('enddate').value;
if (Date.parse(SD) >= Date.parse(ED)) {
return 'The ending date must occur after the starting date.'
}
}
I want to compare strings that are dates
if (user_date < date)
date has yyyy-mm-dd format, so it is OK to compare dates as strings, if the user enters a valid user_date in this format.
Unfortunately, user_date is entered by the user, so it could be invalid. In case if it is invalid (or left empty), I want (user_date < date) always to be true.
I have found to set var user_date=''; if user's date is invalid. Is that a good way to make make (user_date < date) for any valid date?
The same question is for (user_date > date) (more than any date).
I've found to set var user_date='A';
I need it for
if (date1 <= date && date2>= date)
//do something
So it works without any additional if then.
P.S. I don't want to enter var user_date='2222-12-31'; because the algorythm will stop working properly in less than 210 years.
I think that is not possible. But what is possible is to get a date for which a comparison is always false — so functionally it behaves the same as NaN does for numbers. So if you invert the test, thus replace (a <= b) with !(a > b), it would work.
$date = new Date(NaN);
if (!($date1 > $date) && !($date2 < $date)) ...
p.s. What's with the dollar signs? Are you confusing Javascript with PHP or Perl? :)
Why not set your min to be 0000-01-01 and your max to be 9999-12-31 ?
I think you can do somethin glike
var date = '2013-03-12';
var $date = new Date(date);
function onChange(el){
var user_date = el.value;
var udate = new Date(user_date);
if(isNaN(udate.getTime()) || udate < $date){
alert('less')
}
}
Demo: Fiddle
Personally I would first validate the date that the user is entering - don't leave it to chance.
I use my own date extensions library here for this kind of stuff:
DP_DateExtensions
The parseFormat() method will let you easily validate your input. Something like this so do well:
Date.parseFormat(InputString, "YYYY-M-D")
The function returns a valid JavaScript date if the entered string matches the format or null if it doesn't. You obviously don't have to send a user message based on this if you have a default behavior you'd like to apply - but the code itself should "know".
In this case - if you want an invalid date to be less than another, known good date, then there are many ways to do it. Most simple is something like this:
InputDate = Date.parseFormat(InputString, "YYYY-M-D");
if ( InputDate || InputDate < GoodDate ) {
Input Date is Invalid or Falls before good date
} else {
Input Date is Falls after good date
};
You don't need to set "false dates" or guess with the right validation and Boolean logic in play and it will work until the world stops spinning (in theory).
You can you use the compare() method in the library to do any kind of greater/less than comparison to any precision.
Hope this helps.
I have a scenario where i have to compare two DateTime objects
Start DateTime and End DateTime
EndDatetime should be greater than StartDateTime
EndDateTime should be greater than CurrentTime
Now i am trying with simple code as suggested in many of sites and blogs, using ">" or "<" symbols.
E.g: if((Date.parse(startdate)) > (Date.parse(enddate)))
{
alert("Please enter enddate greater than startdate");
}
This works fine if DateTime is in same Month. Even after entering valid datetime range like start datetime being Feb 20th 2011 and End datetime being March 3rd 2011, i still get above alert which is actually wrong.
Can anyone please help, in figuring what is wrong or any one who can provide JS function to compare two DateTime objects.
Thanks.
You should use ".getTime()" to get the timestamp integer and then comparing those.
if(Date.parse(startdate).getTime() > Date.parse(enddate).getTime())
{
alert("Please enter enddate greater than startdate");
}
My guess is that when you try to compare the objects themselves, only their string representations get compared lexicographically (not 100% sure about this though).