How to allow only for dates that are equal and smaller - javascript

Here is my code to find whether the two given dates are equal or not ..
It should allow if today is small or equal. and it should not allow if it is greater date.
var date = '10-11-2015';
var today = '11-11-2016'
alert(today)
alert(date)
if( today <= date )
{
alert("small-or-equal-allow")
}
else
{
alert("larger-not-allow")
}
But its showing not working as expected for few days. What is the mistake and how can i fix it ?

You're comparing strings, not dates. If you want the values to be treated as dates then you need to cast them as dates...
var date = new Date('10-11-2015');
var today = new Date('11-11-2016');
if (today <= date) {
alert("small-or-equal-allow");
}
else {
alert("larger-not-allow");
}

Related

Comparing two dates in when one date is in a previous year

I have this function that determines if two sets of dates are overlapping. When the set of dates are in the same year, it works correctly and returns true if there's overlap. If one of the dates is from a previous year, the comparison fails to detect the overlap.
For instance:
var obj = { startDate1: "02/01/2020",
endDate1: "03/01/2020",
startDate2:"02/05/2020",
endDate2:"02/15/2020" }
Using:
if ((obj.endDate1 >= obj.startDate2 && obj.startDate1 <= obj.endDate2) ||
(obj.endDate2 >= obj.startDate1 && obj.startDate2 <= obj.endDate1)) {
}
Returns true since the dates overlap.
However, when startDate1 is in a different year (2019), like so:
var obj = { startDate1: "12/01/2019",
endDate1: "03/01/2020",
startDate2:"02/05/2020",
endDate2:"02/15/2020" }
The expression above fails to detect the overlap even though startDate1 and endDate1 do in fact overlap with startDate2 and endDate2.
I've tried using moment and regex to format the dates, but to no avail. Any ideas what I'm doing wrong?
Edit: Here's how I'm using moment:
const obj = {
startDate1: moment(new Date(value.startDate)).format("MM/DD/YYYY"),
endDate1: moment(new Date(value.endDate)).format("MM/DD/YYYY"),
startDate2: moment(new Date(startDate)).format("MM/DD/YYYY"),
endDate2: moment(new Date(endDate)).format("MM/DD/YYYY")
};
The values I'm passing in to new Date are iso date strings.
Sorry for the confusion..
Edit #2/Answer:
I just converted the dates using native JS Date.parse.
const obj = {
certStart: Date.parse(value.startDate),
certEnd: Date.parse(value.endDate),
startDate: Date.parse(startDate),
endDate: Date.parse(endDate) };
Using the Native Date function in js
var obj = {
startDate1: "02/01/2020",
endDate1: "03/01/2020",
startDate2:"02/05/2020",
endDate2:"02/15/2020"
};
// Create a clone of obj object and convert values to timestamp.
var $dates = {};
$dates.startDate1 = new Date(obj.startDate1).getTime();
$dates.startDate2 = new Date(obj.startDate2).getTime();
$dates.endDate1 = new Date(obj.endDate1).getTime();
$dates.endDate2 = new Date(obj.endDate2).getTime();
Comparing time:
if (($dates.endDate1 >= $dates.startDate2 && $dates.startDate1 <= $dates.endDate2) ||
($dates.endDate2 >= $dates.startDate1 && $dates.startDate2 <= $dates.endDate1)) {
// etc...
}
Use new Date() or moment.js to create and manipule dates.
var obj = { startDate1: moment("12/01/2019"),
endDate1: moment("03/01/2020"),
startDate2:moment("02/05/2020"),
endDate2:moment("02/15/2020")}
and moment functions to manipulate dates
Despite your tag, it doesn't seem like you are actually formatting the dates using momentjs - unless you aren't sharing some of the code. It really looks like you are making string comparisons. For date comparison in general, I suggest reading the related: Compare two dates with JavaScript
Relevant MDN on Date: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
And don't forget to reference the moment.js docs: https://momentjs.com/docs/
EDIT: As already pointed out, you are using .format(), which returns a display string https://momentjs.com/docs/#/displaying/format/ - so you're still comparing strings instead of dates.
You may want to checkout isBetween: https://momentjs.com/docs/#/query/is-between/
Parse date string to Date, then get its value as a number:
const [m, d, y] = dateStr.split('/').map(Number)
// month is 0-indexed, whereas year and day are 1-indexed
const dateVal = new Date(y, m - 1, d).valueOf()
Then, you can easily compare them with >, <, and so on.
If the date string is in YYYY/MM/DD format then the string comparison will work.
var obj = {
startDate1: "2019/12/01",
endDate1: "2020/03/01",
startDate2: "2020/02/05",
endDate2: "2020/02/15"
}
// this will work
if ((obj.endDate1 >= obj.startDate2 && obj.startDate1 <= obj.endDate2) ||
(obj.endDate2 >= obj.startDate1 && obj.startDate2 <= obj.endDate1)) {
console.log('overlap detected')
}

Javascript: check date in future in dd/mm/yyyy format?

I'm trying to check the users input field to see if it is in the future and if it is in dd/mm/yyyy format but I have no idea why the format part of my code doesn't fire at all! In fact nothing seems to be working on Jsfiddle but at least my "check date in the future" function works locally.
I don't know the correct way of going about this.
to explain this, I've created this FIDDLE
And this is my full javascript code. I need to stay with pure javascript by the way:
function checkdate(){
//var sendDate = document.getElementById('send_year').value + '/' + document.getElementById('send_month').value + '/' + document.getElementById('send_day').value;
var sendDate = document.getElementById('returning_date').value;
sendDate = new Date(Date.parse(sendDate.replace(/-/g,' ')))
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById('error8').innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById('error8').innerHTML = '';
}
if(sendDate.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/))
{
alert('works out');
}
}
could someone please advise on this issue?
Thanks in advance.
One problem is that you are trying to run sendDate.match, but sendDate has been converted into a Date object so it does not have a match method.
You should run your regular expression before you convert it to a Date, in validation, you typically check that the input conforms to a format before you run further validation like range validation.
Date strings should always be manually parsed, you should never allow the Date constructor or Date.parse to parse strings (the Date constructor parses strings in exactly the same way Date.parse does).
To parse and validate a date string is fairly straight forward, just parse the string and see if you get a valid date:
/* Parse a string in d/m/y format. Separator can be any non–digit
** Avoid conversion of two digit dates to 20th century
** Returns an invalid Date if string is not a valid date (per ECMA-262)
**
** #param {string} s - Date string to parse
** #returns {Date}
*/
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Test valid date
document.write(parseDMY('23/01/2016'));
// Test invalid date
document.write('<br>' + parseDMY('35/12/2016'));
Note that this will accept a date like 1/5/16 and treat is as 1 May, 0016. If you want to guarantee that the day and month values have two digits and the year for, then add:
/^\d\d\D\d\d\D\d{4}$/.test(s)
to the validation test at the end. However, I don't like forcing 2 digits for day and month as people don't usually write dates as "01/08/2016", they use "1/8/2016".
First of all, the function needs to be wrapped in <head> (hit the cog in the js tab), otherwise the function can't be found.
But your main problem is that you are using European style of date formatting, so you'll get a "Invalid Date" exception when creating the date. Refer to this question on how to convert it to USA-style and make it available for the Date object (check the reference for all possible uses)
My proposal is:
Date.prototype.fromString = function(str) {
var m = str.match(/([0-9]{2})(-|\/)([0-9]{2})(-|\/)([0-9]{4})/);
if (m == null) {
return null;
}
for (var i = 0; i < m.length; i++) {
if (typeof(m[i]) === 'undefined') {
return null;
};
};
var year = parseInt(m[5]);
var month = parseInt(m[1]) - 1;
var day = parseInt(m[3]);
if (month == 0 || day == 0) {
return null;
}
return new Date(year, month, day);
}
function checkdate(e, obj, errMsgSel){
var sendDate =obj.value;
sendDate = (new Date()).fromString(sendDate);
if (sendDate == null) {
if (e.type == 'blur') {
obj.value = '';
}
return;
}
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById(errMsgSel).innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById(errMsgSel).innerHTML = '';
}
} $(function () {
});
<input onblur="checkdate(event, this, 'error8');" onKeyUp="checkdate(event, this, 'error8');" type='text' name="text1" placeholder='dd/mm/yyyy' id='returning_date'>
<span id='error8' style='color:red;'>format</span> <br><Br>

Failed to compare dates via javascript

I wanted to compare two dates which are in below format:
9/10/2014 5:22 PM
I have two such dates and i want to compare them.
For that i have written below code:
var StartDateTime = ($("#dtpStartDate").data("kendoDateTimePicker")).value().toLocaleString("en-US");
var currentDateTime = new Date();
if (StartDateTime < currentDateTime.toLocaleString()) {
alert("StartDateTime is less");
flagValidation = false;
}
else {
alert("StartDateTime is large");
}
But actually when StartDateTime is less than currentdatetime then also Its showing alert "StartDateTime is large".
Please help me.
How can i compare the dates correctly?
You have convert object to date format to compare and consider all components of date. for your reference (Check the hard coded minutes..)
if(new Date("9/10/2014 5:23 PM") <= new Date("9/10/2014 5:22 PM")){
alert("StartDateTime is less");
}
else{
alert("StartDateTime is large");
}

javascript date validation is not working for today date

I have got below java script code that will validates date range ... when the user entered the today date or any future dates I have set IsValid to true and then will do the save operation ....
for that purpose I have written below code ..
function Save(e) {
var popupNotification = $("#popupNotification").data("kendoNotification");
var container = e.container;
var model = e.model;
var isValid = true;
var compareDate = e.model.DeliveryDate;
alert(compareDate);
var todayDate = new Date();
var compareDateModified = new Date(compareDate)
alert(compareDateModified);
if (compareDateModified > todayDate || compareDateModified === todayDate) {
isValid = true;
}
else
isValid = false;
e.preventDefault();
if (isValid == false)
{
popupNotification.show("Delivery Date should be today date or Greater", "error");
}
$('#Previous').show();
$('#Next').show();
}
Its working fine when I give the future dates but its not working for today date. I also need to check the today's date. I am not able to figure it out the error alert when I try to enter to the today date .
You are comparing two objects of the same type, but different objects, so that will always result in 'unequal'
If you use date.getTime() you will get better results in your comparison - but only if the time component is the same of course.
Think of the Date object like a timestamp. It is based on the unix-style of timestamps (the amount of seconds since 1st January, 1970) so the Date object isn't the day, it is the Date AND the Time.
What you're comparing is the times as well, which could get a little iffy. If only days matter, try using:
fullCompareDate = compareDateModified.getFullYear() + "/" + compareDateModified.getMonth() + "/" + compareDateModified.getDate();
fullTodayDate= todayDate.getFullYear() + "/" + todayDate.getMonth() + "/" + todayDate.getDate();
if(compareDateModified>todayDate||fullCompareDate==fullTodayDate)
{
//Do something
}
This will compare the date and time to make sure they are greater OR check the current date with the compare date (as strings)
Another solution is to blank out the times on both dates:
compareDateModified.setHours(0,0,0,0);
todayDate.setHours(0,0,0,0);
if(compareDateModified>=todayDate)
{
//Do something
}
You are comparing the compareDateModified to todayDate on the millisecond level. To compare at the day level:
var todayDate = new Date();
todayDate.setHours(0,0,0,0);
//you may also have to truncate the compareDateModified to the first
//second of the day depending on how you setup compareDate
if (compareDateModified >= todayDate) {
isValid = true;
}

JavaScript validation for datetime combination comparing

I have two dates i want to throw an alert if astart date is less than enddate
format i use dd/mm/yyyy
time 24 hrs format :HH:MM:SS
var strt_date = 31/03/2014 23:02:01;
var end_date = 01/04/2014 05:02:05;
if(Date.parse(strt_date) < Date.parse(end_date))
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
See the following answer: Compare two dates with JavaScript
Essentially you create two date objects and you can compare them.
var start_date = new Date('31/03/2014 23:02:01');
var end_date = new Date('31/03/2014 23:02:01');
if (end_date < start_date) {
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
(from reading the linked answer it is possible using the Date::gettime method for comparison purposes may be faster than the actual comparing of date objects)
Your timestamps are not quoted as strings, which is throwing a syntax error, add single quotes to them:
var strt_date = '31/03/2014 23:02:01';
var end_date = '01/04/2014 05:02:05';
if((new Date(strt_date)).getTime() < (new Date(end_date)).getTime())
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}
Using .getTime() will compare as numbers, so you can determine if the start date has a greater number than the end date.
DEMO
Try to use the folowing format: Date.parse("YEAR-MONTH-DAYTHOURS:MINUTES:SECONDS")
var strt_date = "2014-03-31T23:02:01";
var end_date = "2014-04-01T05:02:05";
if(Date.parse(strt_date) < Date.parse(end_date))
{
alert("End datetime Cannot Be Less Than start dateime");
return false;
}

Categories