Why is my date comparison not working in JavaScript? [duplicate] - javascript

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 6 years ago.
I have pretty extensively researched this issue, and I've found some useful information, but I haven't been able to solve my problem. All I'm trying to do is parse a date and compare it to another date. Seems simple, right? Here is what I've tried:
function getCurrentDate() { //this function simply returns today's date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
return today;
}
$("#TxtDate").blur(function () {
var projectDueDate = Date.parse($("#lblDueDate").val()); //parses the project due date label to create a date variable
var itemDueDate = new Date($("#TxtDate").val()); //parses the value the user entered into the due date box to create a date variable
var actualProjectDueDate = new Date(projectDueDate);
if (Date.parse(document.getElementById('TxtDate').value) > getCurrentDate()) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtDate").val() = "";
}
});
The if statement isn't working in the TxtDate blur function. It is not showing the alert window, even though I am entering a date that precedes today's date. As you can see, I've tried some different things. Any suggestions?

Your function getCurrentDate is returning a string not a date object and you are comparing it with date object. So you need to parse the return value of getCurrentDate.
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse( getCurrentDate())) {
alert("The date you entered precedes today's date. Please enter a valid date.");
$("#TxtLeaveFrom").val() = "";
}

Date.parse() returns a date object while getCurrentDate() returns a string. Add the Date.parse() there too:
if (Date.parse(document.getElementById('TxtDate').value) > Date.parse(getCurrentDate()))

Related

issue comparing dates on iOS devices [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
I am trying to compare two dates which works properly on every device except the iPhone.Its giving wrong alert on iPhone.
jsfiddle
function play_time() {
var crntTime;
var today = new Date();
var formattedTime = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = yyyy + '-' + mm + '-' + dd;
var crntDatetime = `${today} ${formattedTime}`;
crntTime = new Date(crntDatetime).getTime();
var check = '2020-08-18 23:14:07';
var gameTime = new Date(check).getTime();
if (crntTime <= gameTime) {
alert('Play');
} else {
alert('Later');
}
}
<button onClick="play_time();"> show Time </button>
By using a space between the date and time in your check example, you're straying outside of the specification. That means that the implementation can use local time, or UTC, or refuse to parse it entirely.
Use the date time format in the specification which is basically what you have but with a T instead of space, or use the multi-argument Date constructor (for local time), or Date.UTC (passing the result into the Date constructor) for UTC. If parsing a string ideally always specify Z for UTC or a timezone offset. Date-only forms ("2020-08-19") are parsed in UTC but date-time forms ("2020-08-19T00:00:00") are parsed in local time — but, that changed more than once during the years 2015-2017 so it's a bit risky to rely on it.
In your situation, since you already have the information as separate variables, I would definitely use the multi-argument version of new Date or Date.UTC+new Date (depending on whether you want local or UTC).

Date validation and relative delta between two dates in javascript

I have an interface where I receive a date in this format: Month/Year, ex: 11/2022.
I would like to verify that this is a valid date.
I use the datatables editor. The configuration (see below) of the field works well, but since the user can enter the date himself without going through the calendar, there is a risk that the date entered is incorrect. It doesn't work like an input mask. So i need to validate the date in the code.
{
type: "datetime",
label: "Date:",
name: "Date",
def: function () { return new Date(); },
format: 'MM/YYYY',
fieldInfo: 'Format: Month/Year (ex: 12/2022)',
keyInput: true
}
The date should not be accepted if the difference between this date and today's date is less than 3 months.
It means that, compared to today, all dates before July will have to be rejected.
Currently I can do this with the relativedelta method of the python dateutil module. But as the validation must be done on the client side, I would like to do this in javascript (which I know very little).
The example below shows how to do this. You should take advantage of the HTML 5 input types to validate your dates. You also need to calculate 3 months from now in myEpoch and then compare it to the date/time given
HTML:
<p>
Date & Time: <input id="foo" type="datetime-local" />
</p>
JavaScript:
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
var foo = document.getElementById("foo");
if (foo.value < myEpoch) {
//show a message saying this date is invalid
}
Since user is entering date in MM/yyyy format, so i'm assuming that you take 1 as a date into account, i.e., if input is 03/2020, you would consider it as: 01/03/2020. Right? If
so, then you can do the following to validate this date:-
function isValidDate(inputDate) {
// Unfortunately JS doesn't have any in-built function to validate date in MM/yyyy format. Hence regex comes to the rescue
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
throw new Error('Unable to parse date.');
}
// Check if it is less than 3 months or not.
var isValid = !isLessThan3Months(new Date(finalDate), new Date());
return isValid;
}
function isLessThan3Months(dateToCompare, currentDate) {
var diffYears = currentDate.getFullYear() - dateToCompare.getFullYear();
var diffMonths = currentDate.getMonth() - dateToCompare.getMonth();
var diffDays = currentDate.getDate() - dateToCompare.getDate();
var months = diffYears * 12 + diffMonths;
if (diffDays > 0) {
months += '.' + diffDays;
} else if (diffDays < 0) {
months--;
months +=
'.' +
(new Date(currentDate.getFullYear(), currentDate.getMonth(), 0).getDate() + diffDays);
}
return months < 3;
}
isValidDate('03/2020');
So now, by calling isValidDate with user's input date in MM/yyyy format, you should be able to check if it is valid or not.
For this, you won't need to use any third party javascript library. Just plain javascript is enough.
You should probably use Moment.js, because working with the raw Date object is fiddly.
If you would rather use plain JavaScript, then the following might be of use:
const moreThan3MonthsHence = ({ utcYear, utcMonth },
now = new Date,
target = new Date(Date.UTC(utcYear, utcMonth)),
threeMonthsHence = addMonths(new Date(now.valueOf()), 3)) =>
(target > threeMonthsHence)
const validate = (str,
[utcMonth, utcYear] = str.split('/'),
date = new Date(Date.UTC(+utcYear, (+utcMonth)-1))) =>
moreThan3MonthsHence({ utcYear: date.getUTCFullYear(), utcMonth: date.getUTCMonth() })
const addMonths = (date, months, d = date.getDate()) => {
date.setMonth(date.getMonth() + +months);
// If rolled over to next month, set to last day of previous month
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
// Note: input is one-based months
console.log(validate('07/2020')) // true
console.log(validate('06/2020')) // false
console.log(validate('12/2019')) // false
Notes
now is internally represented as the milliseconds since the Unix epoch. Note this includes the current time of day.
target is the milliseconds since the Unix epoch of midnight on the supplied UTC date.
threeMonthsHence is the milliseconds since the Unix epoch of now (including time of day), plus three months.
validate parses the input string.
addMonths is necessary because the built-in function can roll-over into a new month with unexpected behavior.
Finally to solve my problem I mixed the solutions proposed by #Sumit Parakh and #ControlAltDel.
function isValidDate(inputDate) {
var regex = /^([0-9]{1,2})\/([0-9]{4,4})$/;
var matches = regex.exec(inputDate);
var parsedDate = 0;
if (!matches || matches.length != 3) {
throw new Error('Please provide date in MM/yyyy format');
}
else {
var inputMonth = matches[1]; // Return month from input date
var inputYear = matches[2]; // Return year from input date
var finalDate = inputMonth+ '/01/' + inputYear;
// Check if entered date is valid or not
var parsedDate = Date.parse(finalDate);
if (isNaN(parsedDate)) {
parsedDate = 0;
//throw new Error('Unable to parse date.');
}
return parsedDate;
}
var myEpoch = new Date();
myEpoch.setMonth(myEpoch.getMonth() + 3);
myEpoch = myEpoch.getTime();
finalDate = isValidDate(date_peremption.val());
if (finalDate == 0){
date_received.error("This date is invalid");
}
else if(finalDate < myEpoch) {
date_received.error("The date must be more than three months last");
}
It's not very elegant, but it works. Thanks everyone

Comparing dates in javascript doesn't always work [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 6 years ago.
I am trying to compare two dates to see if one date is less than the other date, so I format both dates, then check if the expiry date is less than today and if it then show an alert message:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var ExpiryDate = result.VATExpiryDate;
var day = ExpiryDate.getDate();
var month = ExpiryDate.getMonth()+1;
var year = ExpiryDate.getFullYear();
if(day<10){
day='0'+day
}
if(month<10){
month='0'+month
}
var ExpiryDate = day+'/'+month+'/'+year;
if(ExpiryDate < today && result.VATAuthNo.length>0)
{
alert("Please note Vat Authorisation Date for " + result.Name + " has expired - " + ExpiryDate);
}
But it seems it doesn't work for all dates. For example if the expiry date is 10/12/2015 it works and the alert message shows. But if the date is 21/06/2016 it doesn't work, even though that date is less than today.
You can compare dates operating directly with date object, not need to convert. javascript is a powerful language mate.
var today = new Date();
var expDate = new Date(2016, 10, 02)
if (today > expDate)
alert("expired");
Use the following method:
if( new Date(first).getTime() > new Date(second).getTime() ) {
// code;
}
var date1 = new Date('2017-02-15');
var date2 = new Date('2017-02-15');
if( date1 === date2 ){
console.log("bot are equal");
}
if( +date1 === +date2 ){
console.log("bot are equal");
}
You are comparing strings - to have correct results you shoud use format like YYYY-mm-dd not dd/mm/YYYY

how to alert if the input date is greater than defined date in js

I am having an input date field in my form. In my date field
i need to alert an error if the input date is greater than any date i define before
here is what i code :
$(document).ready(function () {
var date = new Date(2016,2,1); //the defined date is 1 March 2016
var day = date.getDate();
var month = date.getMonth();
month = month + 1;
if(day < 10){
day = '0' + day;
}
if(month < 10){
month='0'+month;
}
someday = day + '/' + month + '/' + date.getFullYear();
$("#q1 input").blur(function(){ //#q1 is the ID for the input field.
if($('#q1 input').val() > someday){
alert('the input is bigger than the defined');
}else{
alert('the defined is bigger than the input ');
}
});
});
To compare Dates is very straight forward. Most operators coerce the operands to number, and Dates return their time value so to see if today is before or after say 1 March 2016, create two Dates and compare them:
var epoch = new Date(2016,2,1); // Create date for 2016-03-01T00:00:00
var now = new Date(); // Create a date for the current instant
now.setHours(0,0,0,0); // Set time to 00:00:00.000
if (now < epoch) {
alert('Before 1 March, 2016');
} else {
alert('On or after 1 March, 2016');
}
Or a bit more compact:
alert((now < epoch? 'Before':'On or after') + ' 1 March, 2016');
You might want to compare the values as in the date form, not the way you did.
Convert the input value into the form of date and compare it with the variable 'date'.
Compare the input date with the desired date that you defined. For example:
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
If you find it tricky, then there is an awesome js library called moment.js. It is very useful when playing with dates.
$(document).ready(function () {
var date=new Date(2016,2,1); //the defined date is 1 March 2016
var fixedDate = returnDate(date);// convert date in dd/mm/yyyy format
//#q1 input will search a child input inside an #q1 dom element, which probably not the case
// input#q1 will refer to input with id #q1
// You can directly query the input since it has id #q1 so #q1 input is not correct
$("#q1").blur(function(){ //#q1 is the ID for the input field.
var d2 = new Date($('#q1').val());
var inputDate = returnDate(d2); // convert input date in dd/mm/yyyy format
if(inputDate > fixedDate){ // compare two dates
console.log('the input is bigger than the defined');
}else{
console.log('the defined is bigger than the input ');
}
});
});
// Write a general function to convert date in dd/mm/yyyy format
function returnDate(date){
var day=date.getDate();
var month=date.getMonth();
month=month+1;
if(day<10){
day='0'+day;
}
if(month<10){
month='0'+month;
}
var someday=day+ '/' + month + '/' + date.getFullYear();
return someday;
}
JSFIDDLE
EDIT 1
Use ternary operator instead of if-else
inputDate > fixedDate? (console.log("the input is bigger than the defined")):(console.log("the defined is bigger than the input"))
with ternary operator

Date Validation in javascript?

i have problem with date validation in javascript
the problem is i have popup calendar the return a date value
i want to check the date in javascript before send it to parent page
in popup calendar.aspx
function passDateValue(DateValue)
{
window.returnValue=DateValue;
window.close();
return false;
}
in popup calendar codebehind
ClientScript.RegisterStartupScript(GetType(), "SelectDate", "passDateValue('" + clrPopUp.SelectedDate.ToShortDateString() + "')", true);
the function that call the popup calendar and check the returned value
function Calendar_popup(tbClientID)
{
var today = new Date();
var Day = today.getDate();
var Month = today.getMonth()+1;
var Year = today.getFullYear();
if(Month<10){Month = '0'+Month;}
if(Day<10){Day = '0'+Day;}
var todayFormat = Day + "/" + Month + "/" + Year;
datevalue = window.showModalDialog("Calendar_Dialog.aspx?ctlid=" + tbClientID, '',"dialogHeight:250px;dialogWidth:300px;");
var startdate = Date.parse(datevalue);
var enddate = Date.parse(todayFormat);
if (startdate>enddate)
{alert('BirthDate Must be less than today');
return;
}
}
is there anyway to check date ?
thanks!
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=

Categories

Resources