How to compare javascript dates (strings) with a specific format - javascript

I have two dates in a specific format (strings). I need to verify if the current date is lower than the max allowed date:
var date_current = '03_25_2022';
var date_max = '03_30_2022';
The format will always be m_d_Y. Since these are technically strings, what would be the best way to compare them as dates?
I'm using this function but I'm not sure of the approach:
function compareDates(d1, d2){
var parts = d1.split('_');
var d1 = Number(parts[1] + parts[2] + parts[0]);
parts = d2.split('_');
var d2 = Number(parts[1] + parts[2] + parts[0]);
return d1 <= d2;
}

You can first convert these string into date object and then compare their timestamp as follow:
function strToDate(str) {
const splits = str.split('_');
if (splits.length !== 3) {
throw Error("Invalid date");
}
return new Date(splits[2], parseInt(splits[0]) - 1, splits[1]);
}
let dateCurrent = strToDate('03_25_2022');
let dateMax = strToDate('03_30_2022');
console.log(dateMax.getTime() > dateCurrent.getTime())

Related

Check if Date is in Range

I have a date range suppose 2000-01-01 to 2021-06-01. I want to check whether a particular month with a given year falls in this range or not (E.g., month = March and year = 2021) using JavaScript.
Create a reusable function isDateInRange that accepts your three date Strings arguments.
Than you can simply compare your Date Objects using the needed operands:
const isDateInRange = (date, from, to) => {
const d = new Date(date);
const f = new Date(from);
const t = new Date(to);
return (d >= f && d < t);
};
console.log(isDateInRange("2001-01-31", "2000-01-01", "2021-06-01")) // true
console.log(isDateInRange("2050-01-01", "2000-01-01", "2021-06-01")) // false
Here is a solution passing month and year (not a date) as you requested.
const lowerRange = new Date('2000-01-01');
const upperRange = new Date('2021-06-01');
// If month and year are numbers
const monthYearInRange = (year, month) => {
if (typeof month !== 'number') throw new Error('Month should be number');
if (typeof year !== 'number') throw new Error('Year should be number');
// We do this to make sure it is 2 chars.
const mth = month < 10 ? `0${month}` : month;
// Set it to first of the month
const checkVal = new Date(`${year}-${mth}-01`);
if (isNaN(checkVal)) throw new Error(`Year: ${year} and Month: ${month} are not valid.`);
return checkVal <= upperRange && checkVal >= lowerRange;
}
console.log(monthYearInRange(2000, 2)); // true
console.log(monthYearInRange(2030, 2)); // false
console.log(monthYearInRange(2021, 6)); // true
console.log(monthYearInRange(2021, 10)); // false
Just a note on this solution - because ultimately we convert the year/month into a date, when doing this we have to instantiate the date using the ISO format YYYY-MM-DD. If checkVal gets instantiated with a month that is a single character (1 instead of 01) it will still work in most cases - but you will get edge cases breaking because the Date() constructor will add timezone values to the date.
Update: Added NaN check - per #RobG
I tried the following approach and it worked:
function isBetween(n, a, b) {
return (n - a) * (n - b) <= 0
}
var startDate = '2021-03-15';
var endDate = '2021-06-01';
var checkFor = '2021-05-31';
D_1 = startDate.split("-");
D_2 = endDate.split("-");
D_3 = checkFor.split("-");
//console.log(D_1+" "+D_2+" "+D_3);
var startNumber = D_1[0]*100 + D_1[1];
var endNumber = D_2[0]*100 + D_2[1];
var checkNumber = D_3[0]*100 + D_3[1];
var check = isBetween(checkNumber, startNumber, endNumber);
console.log(check);

How can I compare dates of format yyyyMMdd HHmmss.SSS in javascript while the inputs are of charecter format

How can I compare dates of format yyyyMMdd HHmmss.SSS in javascript while the inputs are of charecter format.I tried using date parse and other things.No luck
One way is to convert your dates to ISO-8601 format and load them using new Date() and compare the dates.
The other way is to use 3rd party libs like Moment js (momentjs.com/docs/).
var m1 = moment(dateStr1, 'YYYYMMDD HHmmss.SSS');
var m2 = moment(dateStr2, 'YYYYMMDD HHmmss.SSS');
if (m1 == m2) {}
Using plain JS
function toDate(d) {
var regex = /(\d{4})(\d{2})(\d{2})\s(\d{2})(\d{2})(\d{2})\.(\d{3})/;
var YEAR = 1, MONTH=2, DAY=3, HOUR=4, MIN=5, SEC=6;
var parts = date.match(regex);
return new Date(`${parts[YEAR]}-${parts[MONTH]}-${parts[DAY] ${parts[HOUR]}:${parts[MIN]}:${parts[SEC]}`);
}
var d1 = toDate('20170531 131515.765');
If by "compare dates" you mean if date1 is before date2 (i.e. < or > operators), the format you have will let you compare as strings:
var a = '20170531 231253.475';
var b = '20170531 231254.000';
console.log('a is before b? ' + (a.localeCompare(b) < 0));
console.log('b is before a? ' + (b.localeCompare(a) < 0));
If you want to compare them as Dates, you can parse the strings fairly easily:
var a = '20170531 231253.475';
var b = '20170531 231254.000';
// Parse date string in format yyyymmdd HHmmss.SSS
function parseSpecial(t) {
var y = t.substr(0,4);
var m = t.substr(4,2);
var d = t.substr(6,2);
var h = t.substr(9,2);
var M = t.substr(11,2);
var s = t.substr(13,2);
var S = t.substr(16,3);
return new Date(y, m-1, d, h, M, s, S);
}
console.log('a is: ' + parseSpecial(a).toString() +
'\nb is: ' + parseSpecial(b).toString());
console.log('Is a before b? ' + (parseSpecial(a) < parseSpecial(b)));
console.log('Is b before a? ' + (parseSpecial(b) < parseSpecial(a)));
Of course you should add validation to the parser to ensure you're comparing valid dates and provide default values for any missing parts.

Convert date string into proper date in Javascript

I get an array with dates as string from the server, now I want to filter only day, month and year. How can I format the filter result to a certain date format?
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00', ...];
//wanted result: 2015-02-04 or 04.02.2015
You could convert your what's look to be an ISO Date format like this:
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];
date.map(function(_d) {
var d = new Date(_d)
return d.getFullYear() + '-' + d.getMonth() + 1 + '-' + d.getDay()
}
// if you want to get fancy, you could throw in this function to pad the days and months:
var pad = function (n) {return n<10? '0'+n:''+n;}
var sorted = date.map(function(_d) {
var d = new Date(_d)
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDay())
})
console.log(sorted);
Date can take an argument of a string. Use a for loop to iterate through your list, and then make a new Date object for each one.
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00']
var dateObjects = [];
for (var i = 0; i<date.length; i++) {
d = new Date(date[i]);
dateObjects.push(d);
}
Or, in a single line:
var dateObjects = date.map( function (datestr) {return new Date(datestr)} );
Now, you can find the month, day, and year from one of these by the following methods:
var year = dateObjects[0].getFullYear(); // Gets the year
var month = dateObjects[0].getMonth()+1; // Gets the month (add 1 because it's zero-based)
var day = dateObjects[0].getDate(); // Gets the day of the month
dateObjects[0] is just an example that refers to the first date in the list.
So you can then get your output string like
var dateStrings = dateObjects.map(function (item) {
return item.getFullYear()+"-"+(item.getMonth()+1)+"-"+item.getDate();
})
var date = ['2015-02-04T23:54:00.000+01:00','2015-02-04T23:54:00.000+01:00'];
var newdateobject = [];
$.each( date, function(key, e) {
var a = new Date(e);
newdateobject.push(a.getFullYear()+'-'+(a.getMonth()+1) +'-'+a.getDate());
});
IF the format you mentioned is consistent, then:
date.forEach(function(d) {
d = d.substring(0, 10);
})

Get Month as well as date in my variable - javascript

Hi i am trying to do a IF statement which allows the current date to be compared to the input date.. if the input date is below the current date it will be false.
I have got the date passing through my variable but it only stores the number so for example it compares day 9 to another day, which is not very reliable. I want the variable to take in the month and the year as well, meaning it can compare the ENTIRE DATE.
If there is a better way let me know.
Here is my code
if (this.element.find('#visitdate').length > 0) {
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
if (check < today) {
_errMsg = "Please enter a furture visit date";
return false;
} else {
return true;
}
}
Your line for today's date contains an error:
var today = new Date().getDate;
should be
var today = new Date().getDate();
format as mm/dd/yyyy
var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '
var today = new Date().getDate();
function isFromBiggerThanTo(dtmfrom, dtmto){
var from = new Date(dtmfrom).getTime();
var to = new Date(dtmto).getTime() ;
return from >= to ;
}
or using below
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
and compare
You can try this - it's working fine in my project -
Step 1
First Create javascript function as below.
Date.prototype.DaysBetween = function () {
var intMilDay = 24 * 60 * 60 * 1000;
var intMilDif = arguments[0] - this;
var intDays = Math.floor(intMilDif / intMilDay);
if (intDays.toLocaleString() == "NaN") {
return 0;
}
else {
return intDays + 1;
}
}
Step 2
-
var check = new Date(dateParts[2], dateParts[1], dateParts[0], 0,0,0,0).getDate();
var today = new Date().getDate;
var dateDiff = check .DaysBetween(today);
// it will return integer value (difference between two dates )
if(dateDiff > 0 ){ alert('Your message.......');}
You can have this much easier.
You dont need to check with getDate() property you can just compare 2 dates.
And also is not needed to initialize with hours, minutes and seconds the Date, you only need year, month and date.
Here you have your example simplified
var dateParts = $('#visitdate').val().split('/');
var check = new Date(dateParts[2], dateParts[1], dateParts[0]);
var today = new Date();
if (check < today) {
return false;
} else {
return true;
}
http://jsfiddle.net/wns3LkLv/
Try this:
var user="09/09/2014/5/30";
var arrdt= user.split("/");
var userdt = new Date(arrdt[2], arrdt[1] - 1, arrdt[0],arrdt[3],arrdt[4]);
var currdt = new Date();
if (userdt < currdt) {
alert("userdate is before current date"); //do something
}else{
alert("userdate is after current date"); //do something
}
Thanks for all your answers guys i have fixed it.
I used the getTime function instead of getDate.
Then the check variable had to have a -1 assigned to the month as it was going 1 month to high.
var check = new Date(dateParts[2], dateParts[1]-1, dateParts[0], 0,0,0,0).getTime();
Cheers

Date validation with JavaScript

I have a date string in this format - "DD-MM-YYYY"
this validates that successfully:
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ;
if(!startDate.match(dateFormat)){
alert("'Start Date' must be in format: DD-MM-YYYY");
return false;
I need to check that the inserted date is after today's date(or today's date).
how can i do that with JavaScript?
I've tried this:
http://www.redips.net/javascript/date-validation/
with the separator, didn't work. suggestions?
First, this is your current date in javascript:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1; // Zero indexed
All you need to do, from here, is to compare this with your start date!
Best regards!
check this out maybe it helps to understand the date object.
Check out date.js, specifically...
http://code.google.com/p/datejs/wiki/APIDocumentation#compare
Compares the first date to the second date and returns an number
indication of their relative values. -1 = this is < date. 0 =
values are equal. 1 = this is > date.
The isAfter() and the isBefore() methods might be useful for your problem :)
Download the library here:
http://code.google.com/p/datejs/downloads/detail?name=date.js&can=2&q=
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
You could do this with moment.js pretty easily.
var input = moment(startDate, "DD-MM-YYYY");
if (input < moment()) {
// before today
} else {
// after today
}
We're also adding date validation pretty soon. See more info about validation here: https://github.com/timrwood/moment/pull/306
Something like this should work. Could use some cleanup, but hopefully gets the point across.
var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(\d{4})/;
var dateMatch = startDate.exec(dateFormat);
var today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0); today.setMilliseconds(0);
if ((new Date(dateMatch[3], dateMatch[2] - 1, dateMatch[1])).getTime() >= today.getTime()) {
// Date is after or on today
}
You should check each date getTime() method and compare it. It's plain and simple, you don't need additional frameworks.
Here is an example that parses the dates from the strings, and then compares them:
var todayDate = "10-05-2012";​ // A sample date
var compareDate1 = "10-05-2012";
var compareDate2 = "03-05-2012";
var compareDate3 = "10-07-2012";
compareDates(todayDate, compareDate1);
compareDates(todayDate, compareDate2);
compareDates(todayDate, compareDate3);
function compareDates(date1String, date2String) {
var date1 = parseDate(date1String);
var date2 = parseDate(date2String);
if(date1.getTime() > date2.getTime()) {
alert("First date(" + date1String + ") is older than second date(" + date2String + ").");
} else if(date1.getTime() < date2.getTime()) {
alert("First date(" + date1String + ") is younger than second date(" + date2String + ").");
} else {
alert("The dates are the same day");
}
}
function parseDate(stringDateParam) {
var parsedDay = parseInt(stringDateParam.substring(0,2));
var parsedMonth = parseInt(stringDateParam.substring(3,5))-1;
var parsedYear = parseInt(stringDateParam.substring(6,10));
var parsedDate = new Date(parsedYear, parsedMonth, parsedDay, 0 , 0, 0, 0);
return parsedDate;
}
​
// Output:
//
// First check: The dates are the same day
// Second check: First date(10-05-2012) is older than second date(03-05-2012).
// Third check: First date(10-05-2012) is younger than second date(10-07-2012).
You probably already have a function that parses string to date object, and you should implement a check similar to the one in function compareDates based on getTime() function.
If you have further questions, leave a comment. Good Luck!
JSFiddle working example: click here
Thank you all!
this did the trick:
var today = new Date();
var Tday = today.getDate();
var Tmonth = today.getMonth()+1; // Zero indexed
var Tyear = today.getFullYear();
var aoDate;
var separator= '-';
aoDate = startDate.split(separator);
var month = aoDate[1] - 0;
var day = aoDate[0] - 0;
var year = aoDate[2] - 0;
if(year < Tyear){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month < Tmonth)){
alert("'Start Date' must be today or after today!");
return false;
}
if((year == Tyear) && (month == Tmonth) && (day < Tday)){
alert("'Start Date' must be today or after today!");
return false;
}
Like most I was surprised a what js accepts as the constituent parts of a date. There may be holes in the code below which I would be glad to hear about but this seems to work for me. This assumes a DD/MM/YYYY HH:mm input format.
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1]);
}
// start of validation
var end_time = $('#tbDepartDtTm').val();
end_actual_time = strToDate(end_time);
// convert the date object back to a string in the required format
var dtString = ("0" + end_actual_time.getDate()).slice(-2) + "/" + ("0" + (end_actual_time.getMonth() + 1)).slice(-2) + "/" + end_actual_time.getFullYear() + " " + ("0" + end_actual_time.getHours()).slice(-2) + ":" + ("0" + end_actual_time.getMinutes()).slice(-2);
if (dtString != end_time) {
// if the string isn't the same as entered, it must be invalid. msg is a span element.
msg.textContent = "Depart date is not a valid date.";
return "Error";
}

Categories