Check if a date within in range - javascript

I am trying to check if a date of format mm.dd.yyyy is greater than today and less than the date after 6 months from today.
Here is my code:
var isLinkExpiryDateWithinRange = function(value) {
var monthfield = value.split('.')[0];
var dayfield = value.split('.')[1];
var yearfield = value.split('.')[2];
var inputDate = new Date(yearfield, monthfield - 1, dayfield);
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
alert(inputDate > today);//alert-> true
var endDate = today;
endDate.setMonth(endDate.getMonth() + 6);
alert(inputDate > today);//alert-> false
if(inputDate > today && inputDate < endDate) {
alert('1');
} else {
alert('2');/always alert it
}
}
If I execute isLinkExpiryDateWithinRange('12.08.2012') I wish it will show 1 as this is within the range, but it is displaying 2. Moreover the first alert is showing true and the second one false.
Can anyone please explain what is happening?

Change:
var endDate = today;
to:
var endDate = new Date(today);
See the posts here for how objects are referenced and changed. There are some really good examples that help explain the issue, notably:
Instead, the situation is that the item passed in is passed by value.
But the item that is passed by value is itself a reference.
JSFiddle example

function isLinkExpiryDateWithinRange( value ) {
// format: mm.dd.yyyy;
value = value.split(".");
var todayDate = new Date(),
endDate = new Date( todayDate.getFullYear(), todayDate.getMonth() + 6, todayDate.getDate() +1 );
date = new Date(value[2], value[0]-1, value[1]);
return todayDate < date && date < endDate;
}
isLinkExpiryDateWithinRange("12.24.2012"); // true
isLinkExpiryDateWithinRange("12.24.2020"); // false

Below function checks if date selected is within 5 days from today. Date format used is "DD-MM-YYYY", you can use any format by changing value.split('-')[1] order and split character.
function showMessage() {
var value = document.getElementById("invoiceDueDate").value;
var inputDate = new Date(value.split('-')[2], value.split('-')[1] - 1, value.split('-')[0]);
var endDate = new Date();
endDate.setDate(endDate.getDate() + 5);// adding 5 days from today
if(inputDate < endDate) {
alert("If the due date selected for the invoice is within 5 days, and express settlement fee will apply to this transaction.");
}
}

Related

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

Javascript: how to check if a timestamp belongs to the current day?

I am trying to know if a certain timestamp belongs to today, but I'm getting lost in Javascripts date management.
Is there any way to check if a timestampo belongs to the current day?
Simple check 1st timestamp of both days and compare them.
var ts = 1564398205000;
var today = new Date().setHours(0, 0, 0, 0);
var thatDay = new Date(ts).setHours(0, 0, 0, 0);
if(today === thatDay){
console.log("*** Same day ***");
}
It seems nasty-ish to me however you could do something similar to:
function isInToday(inputDate)
{
var today = new Date();
if(today.setHours(0,0,0,0) == inputDate.setHours(0,0,0,0){ return true; }
else { return false; }
}
This assumes you've already set your input date as a JS date. This will check if the two dates occur on the same day, and return true if so and false if not.
I'm sure someone will come along with a neater way to do this or a case where this fails but as far as I can see this should do the trick for you.
you can really depend on ISO date string with a substr function to compare the two strings
var T=1479288780873; /*assume your timestamp value*/
var theDay=new Date(T);
var today=new Date;
theDay.toISOString().substr(0,10) == today.toISOString().substr(0,10) ? console.log("same day"):null;
You can do something like this :
var day = 24 * 60 * 60 * 1000; //nb millis in a day
var todayTimestamp = new Date(year, month, day).getTime(); // Be careful month is 0 start
//OR
var todayTimestamp = new Date().setHours(0,0,0,0).getTime();
var diff = myTimestamp - todayTimestamp;
if ( diff >= 0 && diff <= day ) {
console.log("timestamp is today");
else {
console.log("timestamp is not today");
}
var timestamp = '2016-11-16 03:14:07.999999';
var datestamp = timestamp.substring(0, 10);
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(), mm, dd].join('-');
};
var date = new Date();
date.yyyymmdd();
console.log(String(datestamp) === String(date.yyyymmdd()));
It depends what format your timestamp is in.
But here is the most basic way to achieve this:
var today = new Date(year, month, day);
var timestamp = //your timestamp;
if (timestamp == timestamp){ //make sure the date formats are the same
//your code
}
I hope this is what you were looking for, there are more methods with the javascript date reference, don't hesitate to look it up.

Only show data on html page where javascript date is within last 10 days

I have javascript array in which the date coming in is in this format
2015-11-25T17:54:19.033
However, I am not really concerned with the time
so I end up with
11/25/15
What I want to do in my loop is to LOOK at the date ( either 2015-11-25T17:54:19.033 or 11/25/15 , whatever is easier) and just set a variable to "NEW" if it is within the last 10 days
I was attempted to play around with this code and it does not give me what I want at all
var dt = "11/25/15";
var today = new Date()
var priorDate = new Date().setDate(today.getDate()-10)
console.log(dt);
console.log(today);
console.log(priorDate);
pseudo code of what i WANT
if ( dt <= today ) {
x = "NEW";
}
So my thoughts are that it need to be in Date objects in javascript but i'm not sure
Update
So say in a loop i have these variables that occur
for ....
dt = 9/13/15
Output = 9/13/15
next time in loop
dt = 11/24/15
Output = NEW - 11/24/15
Working jsfiddle
http://jsfiddle.net/bthorn/yr009hwd/
You are correct. You need to convert the string date to a date time object in javascript to do the comparison.In order to do the comparison, you need to get the millisec of the dates using getTime()
var dt = new Date("11/22/2015");
var today = new Date();
if ( dt.getTime() < today.getTime() ) {
alert('Past');
}
else
alert('future');
To check if the date difference is within 10 days:
var dt = new Date("11/12/2015");
var today = new Date();
var dateDiffDays = Math.ceil((Math.ceil(dt.getTime() - today.getTime()))/(1000 * 3600 * 24));
if( dateDiffDays >= -10 && dateDiffDays <= 10)
alert('date within 10 days');
Depending on the format of your date string, you can probably just do:
var dateToTest = new Date(dt);
//get 10 days earlier
dateToTest.setDate(dateToTest.getDate() - 10);
var today = new Date();
if ( dateToTest < today ) {
x = 'NEW';
}
//see if a date is within the last 10 days
var tenDaysAgo = new Date(); //current date
tenDaysAgo.setDate(tenDaysAgo.getDate() - 10); //ten days ago
//if you don't care about the time
tenDaysAgo.setHours(0);
tenDaysAgo.setMinutes(0);
tenDaysAgo.setSeconds(0);
tenDaysAgo.setMilliseconds(0);
var someDateToTest = new Date('11-1-2015');
if (tenDaysAgo > someDateToTest) {
//this is new
x = 'NEW';
}

Check if one date is between two dates

I need to check if a date - a string in dd/mm/yyyy format -
falls between two other dates having the same format dd/mm/yyyy
I tried this, but it doesn't work:
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var from = Date.parse(dateFrom);
var to = Date.parse(dateTo);
var check = Date.parse(dateCheck );
if((check <= to && check >= from))
alert("date contained");
I used debugger and checked, the to and from variables have isNaN value.
Could you help me?
Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
console.log(check > from && check < to)
Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.
Something like
if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime())) alert("date contained");
Try what's below. It will help you...
Fiddle : http://jsfiddle.net/RYh7U/146/
Script :
if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
alert("Availed");
else
alert("Not Availed");
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
Here is a Date Prototype method written in typescript:
Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
return !minDate ? true : this.getTime() >= minDate.getTime()
&& !maxDate ? true : this.getTime() <= maxDate.getTime();
};
I did the same thing that #Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];
dates.forEach(element => {
let parts = element.split("/");
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
if (date >= from && date < to) {
console.log('dates in range', date);
}
})
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle:
https://jsfiddle.net/zm75cq2a/
Suppose for example your date is coming like this & you need to install momentjs for advance date features.
let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)
let format = "MM/DD/YYYY";
let startDate: any = moment().format(format);
let endDate: any = moment().add(30, "days").format(format);
let compareDate: any = moment(cmpDate).format(format);
var startDate1 = startDate.split("/");
var startDate2 = endDate.split("/");
var compareDate1 = compareDate.split("/");
var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);
if (checkDate > fromDate && checkDate < toDate) {
... condition works between current date to next 30 days
}
This may feel a bit more intuitive. The parameter is just a valid date string.
This function returns true if the date passed as argument is in the current week, or false if not.
function isInThisWeek(dateToCheck){
// Create a brand new Date instance
const WEEK = new Date()
// create a date instance with the function parameter
//(format should be like dd/mm/yyyy or any javascript valid date format )
const DATEREF = new Date(dateToCheck)
// If the parameter is a not a valid date, return false
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Get separated date infos (the date of today, the current month and the current year) based on the date given as parameter
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date by substracting the day index (number) in the week from the day value (count)
//in the month (like october 15th - 5 (-> saturday index)) and +1 because
//JS weirdly starts the week on sundays
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
Try this
var gdate='01-05-2014';
date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
if(parseInt(date) < parseInt(Date.now()))
{
alert('small');
}else{
alert('big');
}
Fiddle
This question is very generic, hence people who are using date libraries also check for the answer, but I couldn't find any answer for the date libraries, hence I am posting the answer for Luxon users.
const fromDate = '2022-06-01T00:00:00.000Z';
const toDate = '2022-06-30T23:59:59.999Z';
const inputDate = '2022-08-09T20:26:13.380Z';
if (
DateTime.fromISO(inputDate) >= DateTime.fromISO(fromDate) &&
DateTime.fromISO(inputDate) <= DateTime.fromISO(toDate)
) {
console.log('within range');
} else {
console.log('not in range');
}

javascript date validation - checking two dates

i have two input box for getting date value in the format "dd/mm/yyyy".
i have to create coupon for a shop, so i have to check 1st date should be from tomorrow.
for ex. if today is 5th sep, then 1st date should not be before 6th sep.
and 2nd date should be atleast 1day greater than the 1st date. if user entered 1st date as 10th sep, then 2nd date should not be same or before 10th sep.
so if a user enters 31st jan 2013 ( 31/01/2013) as 1st date then 2nd date can be 1st feb or any date after 1st feb. so i hvae to check the date validation also.
for date validation i am using the following code -
function chkdate(y,m,d)
{
var date = new Date(y,m-1,d);
month1 = date.getMonth()+1;
date1 =date.getDate();
if(month1 <10)
{
month1 = "0"+month1;
}
if(date1 <10)
{
date1 = "0"+date1;
}
var convertedDate =""+date.getFullYear() + (month1) + date1;
var givenDate = "" + y + m + d;
return ((givenDate==convertedDate)?true:false);
}
i am callling above function inside a function -
function generate_coupon()
{
var f_arr = from_date.split("/"); //from_date is from 1st input date value.
var f_day = f_arr[0];
var f_month =f_arr[1];
var f_year =f_arr[2];
var t_arr = to_date.split("/"); //to_date is from 2nd input date value.
var t_day = t_arr[0];
var t_month =t_arr[1];
var t_year =t_arr[2];
if (chkdate(f_year,f_month,f_day)== true && chkdate(t_year,t_month,t_day)== true)
{
}
else
{
alert('Enter Valid Date - dd/mm/yyyy');
}
}
in that if condition i have to check both date values - the 1st date value is from tomorrow or not and 2nd date value should differ from 1st date by atleast 1 day. if both conditions are true then i wil generate a coupon or else i will alert invalid date.
how should i do it ??
rather doing this type of validation, i think it will be more easy for you that you fill the other date field you self using some defined code. and made those fields UN-editable
Farid has made a good point, however if your base date is dynamic something like this should work:
function isValidInput(date1, date2) {
return date2 >= getNextDate(date1);
}
function getNextDate(date) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
var date_ms = date.getTime();
var nextDate_ms = date_ms + ONE_DAY;
var nextDate = new Date(nextDate_ms);
// Make sure to get rid of time, so that it's always at 00:00:00 hour.
return new Date(nextDate.getYear(), nextDate.getMonth(), nextDate.getYear());
}
function checkDates(d1, d2) {
if (d1 instanceof Date && d2 instanceof Date) {
var today = new Date();
today.setHours(0, 0, 0, 0);
if (date1.getTime() < (today.getTime() + 86400000)) {
return "First date should be after today";
}
if (date2.getTime() < (date1.getTime() + 86400000)) {
return "Second date should be after First date";
}
return "Dates are valid";
}
return "One or more invalid date";
}
var date1Str = "6/9/2012";
var date2Str = "7/9/2012";
var date1Arr = date1Str.split("/");
var date2Arr = date2Str.split("/");
var date1 = new Date(date1Arr[2], date1Arr[1] - 1, date1Arr[0]);
var date2 = new Date(date2Arr[2], date2Arr[1] - 1, date2Arr[0]);
alert(checkDates(date1, date2));
Try this
function generate_coupon() {
var from_date = document.getElementById("fromDate");
var to_date = document.getElementById("toDate");
var from = new Date(from_date.value);
var to = new Date(to_date.value);
var today = new Date();
var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
if (from >= tomorrow && to > from) {
} else {
alert('Enter Valid Date - dd/mm/yyyy');
}
}​

Categories

Resources