Compare present date to previous/next date [duplicate] - javascript

I have two string dates in the format of m/d/yyyy. For example, “11/1/2012”, “1/2/2013”. I am writing a function in JavaScript to compare two string dates. The signature of my function is
bool isLater(string1, string2), if the date passed by string1 is later than the date passed by string2, it will return true, otherwise false.
So, isLater(“1/2/2013”, “11/1/2012”) should return true. How do I write a JavaScript function for this?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
alert ("Error!");
}
Demo Jsfiddle
Recently found out from a comment you can directly compare strings like below
if ("2012-11-01" < "2012-11-04") {
alert ("Error!");
}

You can simply compare 2 strings
function isLater(dateString1, dateString2) {
return dateString1 > dateString2
}
Then
isLater("2012-12-01", "2012-11-01")
returns true while
isLater("2012-12-01", "2013-11-01")
returns false

Parse the dates and compare them as you would numbers:
function isLater(str1, str2)
{
return new Date(str1) > new Date(str2);
}
If you need to support other date format consider a library such as date.js.

Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answer does not work. The answer by vitran does work but has some JQuery mixed in so I reworked it a bit.
// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2
function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}
P.S. would have commented directly to vitran's post but I don't have the rep to do that.

This worked for me in nextjs/react
import { format, parse, isBefore } from "date-fns";
...
{isBefore(new Date(currentDate), new Date(date)) ? (
<span>Upcoming Event</span>
) : (
<span>Past Event</span>
)}
...
isBefore(date, dateToCompare)
https://date-fns.org/docs/isBefore

You can use "Date.parse()" to properly compare the dates, but since in most of the comments people are trying to split the string and then trying to add up the digits and compare with obviously wrong logic -not completely.
Here's the trick. If you are breaking the string then compare the parts in nested format.
Compare year with year, month with month and day with day.
<pre><code>
var parts1 = "26/07/2020".split('/');
var parts2 = "26/07/2020".split('/');
var latest = false;
if (parseInt(parts1[2]) > parseInt(parts2[2])) {
latest = true;
} else if (parseInt(parts1[2]) == parseInt(parts2[2])) {
if (parseInt(parts1[1]) > parseInt(parts2[1])) {
latest = true;
} else if (parseInt(parts1[1]) == parseInt(parts2[1])) {
if (parseInt(parts1[0]) >= parseInt(parts2[0])) {
latest = true;
}
}
}
return latest;
</code></pre>

If your date is not in format standar yyyy-mm-dd (2017-02-06) for example 20/06/2016. You can use this code
var parts ='01/07/2016'.val().split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts ='20/06/2016'.val().split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 > d2

Related

Why is my custom validation in Angular2 not working

Here are two angular2 custom validations that I wrote, the first one validateAge works, but the second one validateDob does not ... the difference is the validateAge uses the component that I am on and is a text based field, the second one needs to use a Date Entry field and find the difference between today's date and the birthdate to find the actual age and then measure it against the age field. but something is not right ... any ideas
function validateAge(control: FormControl): { [s: string]: boolean } {
if (parseInt(control.value) <= 0) {
return {invalidAge: true};
}
}
function validateDob(control: FormControl): {[s:string]: boolean}{
var today = new Date();
var calcAge = today - control.value;
if (calcAge != parseInt([{age}]) ){
return {invalidDate: true}
}
}
The issue you have here is that your control.value is not a Date object, but rather the string representation.
var today = new Date();
Difference in milliseconds between the current timestamp and the entered value
var diff = today - new Date(control.value);
divide by ms per year and take the floor
var calcAge = Math.floor(diff/ (1000*60*60*24*365)));
Now do whatever comparison you need against the appropriate value. You didn't show us what your age object is so I don't actually know what comparison you're looking for.
if (calcAge < someAgeThreshold) ){
return {invalidDate: true}
} else {
return null;
}
Also note that with custom validation the validator returns no error when you return null and anything with a value is considered to have an error.

Compare dates as strings in typescript

I am trying to compare two dates as strings in typescript. The input I have is as below :-
startWindow = '05/2014'
endWindow = '05/2018'
I need to write a function to check if the start Window is greater than the end Window.
Both the inputs are of string type.
Thanks
You can convert it to a date and then compare them:
function convertDate(d)
{
var parts = d.split('/');
return new Date(parts[1], parts[0]);
}
var start = convertDate('05/2014');
var end = convertDate('05/2018');
alert(start < end);

Sort java script array of formatted date

I have an javascript array of date which is formatted in a particular way like MM/DD/YYYY. How can I use javascript sort function to sort this array?
You can use Array.sort, but you need to pass a custom comparison function which converts the values to Dates and compares those, instead of just the string value:
var arr = ['07/01/2014', '04/02/2014', '12/11/2013'];
arr.sort(function(a, b) {
// convert both arguments to a date
var da = new Date(a);
var db = new Date(b);
// do standard comparison checks
if(da < db) {
return -1;
} else if(da > db) {
return 1;
} else {
return 0;
}
});
// print the result
var result = document.getElementById('result');
for(var i = 0; i < arr.length; ++i)
{
result.value = result.value + '\n' + arr[i];
}
<textarea id="result" rows="5" cols="50"></textarea>
Are the dates stored as strings or as Date objects? You can convert each string into a date object by using the Date constructor like new Date('MM/DD/YYYY'). This will give you Date objects and make it much easier to compare. To compare Dates and sort them, just grab their values using the getTime() function to get their value in milliseconds and compare the numbers.

How to test different format of dates in javascript / jquery?

I am developing a application. In this application have a input field. where the user can input the dates by different formats like
ddmmyy, ddmmyyyy, dd-mm-yy, mm-dd-yy
And I need to verify the date whether that valid or not. I can able to validate this way:
YYYY-MM-DD using:
var myDate = new Date("1987-08-06") // it returns me the date while this valid.
But I can't able to validate with other formats. how can i validate that?
example:
var myDate = new Date("08-06-1987")..etc?
I developed my app using jQuery. I am looking some solution without using a plug-in. since i used no.of plugins already.
thanks in advance!
I would do it with regular expressions. You could define a regexp pattern for each of your formats. Then you can test if the String from the input field matches any of the pattern.
Somthing like this:
var regExpDDMMYY = /[0-9]{2}[0-1][0-9][0-9]{2}/g;
var regExpddmmyyyy = ...;
...
...
if (regExpDDMMYY.test(yourInputStringFromDateField)) {
// handleDateAs DDMMYY
} else if (regExpddmmyyyy .test(yourInputStringFromDateField)) {
...
} else {
throw new YourException();
}
You can find an example here:
http://www.w3schools.com/js/js_regexp.asp
Unfortunately, there's no "parseExact" in native JS, that would also be crossbrowser. So you either need to use Date.js library or write some converter.
For this task i'd recommend you to use "Chain of responsibility" pattern
function DateTimeParser() {
this.parse = function (input) {
for (var key in Parsers) {
var result = Parsers[key].parse(input);
if (result !== null)
return result;
}
return null;
};
this.parseExact = function (input, format) {
var parser = Parsers[format];
return parser ? parser.parse(input) : null;
};
var ConcreteDateTimeParser = function (expression, parser) {
this.parse = function (input) {
if (!input.match(expression))
return null;
var result = parser(input);
return isNaN(result.getDate()) ? null : result;
};
};
var Parsers = {
"dd-mm-yyyy": new ConcreteDateTimeParser(/\d{2}\-\d{2}\-\d{4}/, function (input) {
var dd = parseInt(input.slice(0, 2)),
mm = parseInt(input.slice(3, 5)),
yyyy = parseInt(input.slice(-4));
return new Date(yyyy, mm, dd);
}),
"ddmmyyyy": new ConcreteDateTimeParser(/\d{8}/, function (input) {
var dd = parseInt(input.slice(0, 2)),
mm = parseInt(input.slice(2, 4)),
yyyy = parseInt(input.slice(-4));
return new Date(yyyy, mm, dd);
})
};
};
var instance = new DateTimeParser();
instance.parse('22122012');
instance.parseExact('22122012', 'ddmmyyyy');
instance.parseExact('22122012', 'dd-mm-yyyy'); // null
From this you can extend your Parsers lib with additional parsers. You also can use different sets of parsers by passing them into DateTimeParser as a constructor argument. My code is pretty trivial, for i didn't want to write it mega-deep, just wanted to show the way =)

Regular Expression for MM/DD/YYYY in Javascript

I've just written this regular expression in javaScript however it doesn't seem to work, here's my function:
function isGoodDate(dt){
var reGoodDate = new RegExp("/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/");
return reGoodDate.test(dt);
}
and this is how I call it in my form validation
if(!isGoodDate(userInput[1].value)){
alert("date not in correct format of MM/dd/YYYY");
return false;
}
now I want it to return MM/DD/YYYY however if I put a valid date in it raises the alert? Any ideas anyone?
Attention, before you copy+paste: The question contains some syntactic errors in its regex. This answer is correcting the syntax. It is not claiming to be the best regex for date/time parsing.
Try this:
function isGoodDate(dt){
var reGoodDate = /^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/;
return reGoodDate.test(dt);
}
You either declare a regular expression with:
new RegExp("^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$")
Or:
/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/
Notice the /
Maybe because you are declaring the isGoodDate() function, and then you are calling the isCorrectDate() function?
Try:
function isGoodDate(dt){
var reGoodDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
Works like a charm, test it here.
Notice, this regex will validate dates from 01/01/1900 through 31/12/2099. If you want to change the year boundaries, change these numbers (19|20) on the last regex block. E.g. If you want the year ranges to be from 01/01/1800 through 31/12/2099, just change it to (18|20).
I agree with #KooiInc, but it is not enough to test for NaN
function isGoodDate(dt){
var dts = dt.split('/').reverse()
,dateTest = new Date(dts.join('/'));
return !isNaN(dateTest) &&
dateTest.getFullYear()===parseInt(dts[0],10) &&
dateTest.getMonth()===(parseInt(dts[1],10)-1) &&
dateTest.getDate()===parseInt(dts[2],10)
}
which will handle 29/2/2001 and 31/4/2011
For this script to handle US dates do
function isGoodDate(dt){
var dts = dt.split('/')
,dateTest = new Date(dt);
return !isNaN(dateTest) &&
dateTest.getFullYear()===parseInt(dts[2],10) &&
dateTest.getMonth()===(parseInt(dts[0],10)-1) &&
dateTest.getDate()===parseInt(dts[1],10)
}
Add this in your code, it working perfectly fine it here.
click here http://jsfiddle.net/Shef/5Sfq6/
function isGoodDate(dt){
var reGoodDate = /^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
I don't think you need a regular expression for this. Try this:
function isGoodDate(dt){
var dts = dt.split('/').reverse()
,dateTest = new Date(dts.join('/'));
return isNaN(dateTest) ? false : true;
}
//explained
var dts = dt.split('/').reverse()
// ^ split input and reverse the result
// ('01/11/2010' becomes [2010,11,01]
// this way you can make a 'universal'
// datestring out of it
,dateTest = new Date(dts.join('/'));
// ^ try converting to a date from the
// array just produced, joined by '/'
return isNaN(dateTest) ? false : true;
// ^ if the date is invalid, it returns NaN
// so, if that's the case, return false
Validate (DD-MM-YYYY) format :)
function isGoodDate(dt) {
var reGoodDate = /^(?:(0[1-9]|[12][0-9]|3[01])[\-.](0[1-9]|1[012])[\-.](19|20)[0-9]{2})$/;
return reGoodDate.test(dt);
}
Try the below code which accepts following date formats:
MM-DD-YYYY, MM-DD-YY, DD-MM-YYYY, DD-MM-YY, MM/DD/YYYY, MM/DD/YY,
DD/MM/YYYY, DD/MM/YY, MM\DD\YYYY, MM\DD\YY, DD\MM\YYYY, DD\MM\YY
function isGoodDate(dt) {
var reGoodDate = /(?:((0\d|[12]\d|3[01])|(0\d|1[012]))[\-|\\|\/]((0\d|1[012])|(0\d|[12]\d|3[01]))[\-|\\|\/](((19|20)\d{2})|\d\d))/;
return reGoodDate.test(dt);
}
(/^(0[1-9]|1[012])- /.- /.\d\d$/)
You can use this will work definitely and this is for MM/DD/YYYY

Categories