How to check if any date from array is in date range? - javascript

Hope you are all well.
I need to check if any date from array
var arrayDates = ["2013-07-26", "2013-07-27"];
is in date range of
var startDate = new Date("2013-07-10");
var endDate = new Date("2013-07-10");
I am really stuck and started to confuse myself. Can anyone help me with that please.
P.S. Dates above are for example, they will be dynamic.
Thank you!

You will need to use real date objects rather than strings.
maybe have a look at using dateJs for parsing dates
http://www.datejs.com/
But really you need to iterate through the array of dates and check if they fall between the tick value of your start and end dates.
Try this:
var arrayDates = [];
arrayDates.push(new Date(2013, 7 , 26));
arrayDates.push(new Date(2013, 7 , 27));
var startDate = new Date("2013-07-10");
var endDate = new Date("2013-07-10");
for(i = 0; i < arrayDates.length; i++){
if(arrayDates[i] >= startDate && arrayDates[i] <= endDate) {
alert('Yes');
}
}

Another method - http://jsfiddle.net/Mh5vn/
var ds = ["2013-07-26", "2013-07-27"];
Array.prototype.between = function(arg) {
var d1 = new Date(this[0]),
d2 = new Date(this[1]),
d3 = new Date(arg);
return (d1.getTime() <= d3.getTime() && d3.getTime() <= d2.getTime());
}
console.log( ds.between('2013-07-26') );
// true
console.log( ds.between('2013-07-28') );
// false

After you have the date objects you can compare them in a pretty straight forward way. See this link at the bottom.
I see your question is tagged jquery, so you could do something like this:
$.each(arrayDates, function(i, val) {
if (val > endDate || val < startDate)
{
//Date is outside of that range
}
});

Hopefully you can convert these dates to numbers and compare them, here an example :
var arrayDates = ["2013-07-26", "2013-07-27"];
var unDash = function (string) {
return string.replace(/-/g, "")
}
var dateInRange = function (date, startDate, endDate) {
date = unDash(date)
startDate = unDash(startDate)
endDate = unDash(endDate)
return date > startDate && date < endDate
}
// You now filter your array to retrieve your dates
var dates = arrayDates.filter(function (date) {
return dateInRange(date, '2013-07-10', '2013-07-31')
})

Related

Filtering date between two dates in javascript

I was trying to filter the data between two dates.
But i am not able to achieve
Where the Detaileddata is my array having set of data. In which I have the date as
date = {01.07.2020,02.07.2020,03.07.2020,.....18.08.2020}
where date has the values in the format [DD.MM.YYYY],
But the result i am able to acheive is only the data having 01.07.2020 and 18.08.2020. But I want to display the data between the 01.07.2020 and 18.08.2020
Typescript part
var startDate = "01.07.2020";
var endDate = "18.08.2020";
this.Detaileddata = this.Detaileddata.filter((item) => {
return (item.date >= startDate && item.date <= endDate);
})
console.log("result"+this.detaileddata);
The better way always to use library like date-fns or moment.js. Using vanilla approach. You can convert date in timestamp. I am assuming you are getting these date:
var startDate = "01.07.2020";
var endDate = "18.08.2020";
const detailedData = [{date:"01.07.2020"},{date:"20.07.2020"},{date:"25.07.2020"},{date:"01.08.2020"},{date:"18.08.2020"},{date:"01.09.2020"},{date:"01.10.2020"}]
const filteredDate = detailedData.filter(item => {
let itemDate = item.date.split('.').reverse().join("-")
let startDateModified = startDate.split('.').reverse().join("-")
let endDateModified = endDate.split('.').reverse().join("-")
return (new Date(itemDate).getTime() >= new Date(startDateModified).getTime() && new Date(itemDate).getTime() <= new Date(endDateModified).getTime());
})
console.log("result",filteredDate);

Check if date/time is BETWEEN two other date/times Javascript

var startDateTime = '15.04.2019 00:15';
var endDateTime = '17.05.2019 18:35';
var checkDateTime = '16.04.2019 13:15';
function(checkDateTime, startDateTime, endDateTime) {
// need codes to return true or false,.
// check "checkDateTime" is between "startDateTime" to "endDateTime"
}
Try this code:
var startDateTime = getDate('15.04.2019 00:15');
var endDateTime = getDate('17.05.2019 18:35');
var checkDateTime = getDate('16.04.2019 13:15');
function isBetween(checkDateTime, startDateTime, endDateTime) {
return (checkDateTime >= startDateTime && checkDateTime <= endDateTime);
}
function toDate(str){
var [ dd, MM, yyyy, hh, mm ] = str.split(/[. :]/g);
return new Date(`${MM}/${dd}/${yyyy} ${hh}:${mm}`);
}
console.log(isBetween(checkDate,startDate,endDate));
To compare it one time falls between a time interval on the same day use: -
var startTime = "00:35";
var endTime = "18:15";
var checkTime = "13:00";
function getMinutes(timeString){
let [hh, mm] = timeString.split(":");
return parseInt(hh)*60 + parseInt(mm);
}
function isTimeBetween(checkTime,startTime,endTime){
checkTime = getMinutes(checkTime);
return (checkTime >= getMinutes(startTime) && checkTime <= getMinutes(endTime));
}
console.log(isTimeBetween(checkTime,startTime,endTime));
You can use new Date().getTime() to get the number of milliseconds since the Unix Epoch. So that you can compared the date/time with the result from this function. You can do sth like that:
return new Date(startDateTime).getTime() <= new Date(checkDateTime).getTime() <= new Date(endDateTime).getTime();
Check this out:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
I would suggest to check if your checkDateTime is greater than your startDateTime and less then endDateTime.
function checkDateTime(checkDateTime, startDateTime, endDateTime) {
return (new Date(startDateTime) >= new Date(checkDateTime))
&& (new Date(checkDateTime) <= new Date(endDateTime));
}
Here is yet another option which adds the method directly to the Date prototype:
var startDateTime = new Date('04/15/2019 00:15');
var endDateTime = new Date('05/17/2019 18:35');
var checkDateTime = new Date('04/16/2019 13:15');
var outOfRangeDate_EARLY = new Date('01/16/2019 13:15');
var outOfRangeDate_LATE = new Date('06/16/2019 13:15');
Date.prototype.inRange = function(startDate, endDate){
var this_ms = this.getTime();
return ( this_ms >= startDate.getTime() && this_ms <= endDate.getTime() )
}
/* Tests */
console.log('expected: true', 'actual:', checkDateTime.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_EARLY.inRange(startDateTime, endDateTime))
console.log('expected: false', 'actual:', outOfRangeDate_LATE.inRange(startDateTime, endDateTime))
This way, with any date you have var someDate, you can just call someDate.inRange(startDate, endDate). Sometimes, however, messing with the native prototypes can come back to haunt you if not careful. If so, having a separate function as answered by the others is very good.
Lastly, it's very important that the date strings are formatted properly before creating the Date objects, otherwise you'll encounter Invalid Date a lot. I hope this helps.

Array of days in between months

I have two dates: Startdate and enddate
startdate = "10/10/2018" enddate = "03/09/2019"
I am trying to create an array of dates between those 2 dates. I have the following code.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}
Then calculate the number of days between those months in between.
10/10/2018 to 11/10/2018 = 30 days
11/10/2019 to 12/10/2018 = 30 days or so depending on number of days between the 2 dates and then create an array of the dates.
[30,30,31....till end date]
function daysBetween(date1, date2 )
{
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var dayDifference = Math.ceil(timeDiff / (1000 * 3600 * 24));
return dayDifference;
}
I tried the following code and it's returning the array of number of dates however, it's not accurate. It keeps returning 32 days in October. The output it's giving right now is as follows. I am not sure what i am doing wrong here but it looks like it's only going till February and displaying the result.
Any help will be appreciated. Thank you.
Output: [32,30,31,31,28]
var dateArr = getDateArray(z, y);
console.log(dateArr);
var dayCounts = "";
for (var x = 0; x < dateArr.length-1; x++)
{
dayCounts += daysBetween(dateArr[x], dateArr[x+1]);
}
console.log("datearrlength" + dateArr.length);
console.log(dayCounts);
i think this will work for you,
Date.prototype.addDay= function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getDateBwStartandEnd(sdate, edate) {
var dateArray = new Array();
var currentDate = sdate;
while (currentDate <= edate) {
dateArray.push(new Date (currentDate));
currentDate = currentDate.addDay(1);
}
return dateArray;
}
** Shamelessly copied from web, but this works fine for me.
While the following doesn't answer your question it is an alternative approach to the overall problem you are attempting to solve.
One approach would be to simply get the time difference between the two dates and then divide by the number of microseconds in a day. As you will notice though it is not exact and so a floor is used to get the days. There are other concerns with this approach as well such as date ranges before the epoch but it is a very simplistic approach and might work depending on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
const start = (new Date(startDate)).valueOf();
const end = (new Date(endDate)).valueOf();
const timeBetween = end - start;
console.log({timeBetween, days: Math.floor(timeBetween/86400000)});
A slightly more robust is to essentially use a counter that increments itself by adding 1 day to the counter and the start date while the start date is less than the end date. Again, there are some concerns with this approach but that also depends on your needs.
const startDate = '10/10/2018';
const endDate = '03/09/2019';
let start = new Date(startDate);
const end = (new Date(endDate)).valueOf();
let daysBetween = 0;
while (start.valueOf() < end) {
daysBetween++;
start.setDate(start.getDate() + 1);
}
console.log(daysBetween);
Finally, a more robust solution to avoid the variety of issues with manipulating and working with dates is to use a library like momentjs. Using its difference method would look like the following.
const start = moment([2018, 10, 10]);
const end = moment([2019, 3, 9]);
console.log(end.diff(start, 'days'));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Using the following code worked for me. I added 1 extra month to my end date and it gives the proper date range. Also, instead of Math.ceil, i used Math.round and it gives the right number of date.
function getDateArray (start, end) {
var arr = [];
var startDate = new Date(start);
var endDate = new Date(end);
endDate.setMonth( endDate.getMonth());
while (startDate <= endDate) {
arr.push(new Date(startDate));
startDate.setMonth(startDate.getMonth() + 1);
}
return arr;
}

How to get the holidays date in my case?

I am trying to get the holidays of given range of dates.
For example:
var holiday = ['2014-01-01','2014-07-04','2014-12-24', '2014-12-25'...other holidays elements ];
var startDate = '2014-08-01'
var endDate = '2014-12-30';
var holidays=getHolidays(startDate, endDate);
//console.log(holidays) -> output 2014-12-24 and 2014-12-25.
getHolidays = function(startDate, endDate) {
var holidays=[];
//not sure how to get holidays here....
return holidays
}
I was hoping to write a function to get 2014-12-24 and 2014-12-25. My brain is fried now and I don't know what's the best approach on this. Can anyone help me about it? Thanks a lot!
The solution is to use filter function of array. The first parameter is the array you need to filter, and in your case, it's ['2014-01-01', '2014-07-04', '2014-12-24', '2014-12-25'].
var getHolidays = function(holiday,startDate, endDate) {
return holiday.filter(function(element){
var start = new Date(startDate);
var end = new Date(endDate);
var temp = new Date(element);
return temp >= start && temp <= end;
});
}
var holiday = ['2014-01-01', '2014-07-04', '2014-12-24', '2014-12-25'];
var startDate = '2014-08-01'
var endDate = '2014-12-30';
var holidays = getHolidays(holiday,startDate, endDate); //["2014-12-24", "2014-12-25"]
It works exactly as what you expect as shown in
JSFiddle
You could try turning them into date objects, and then comparing them that way. Something like:
var holidays = ['2014-01-01','2014-07-04','2014-12-24', '2014-12-25'];
var startDate = '2014-08-01';
var endDate = '2014-12-30';
var getHolidays = function(startDate, endDate) {
var startTime = new Date(startDate).getTime();
var endTime = new Date(endDate).getTime();
var output = [];
holidays.forEach(function(holiday) {
var holidayTime = new Date(holiday).getTime();
if (holidayTime >= startTime && holidayTime <= endTime) {
output.push(holiday);
}
});
return output;
}
var holidays = getHolidays(startDate, endDate);
console.log(holidays);
As plain strings, the getHolidays function can be:
// Get holidays between two dates
function getHolidays(startDate, endDate) {
var output = [];
var i = 0;
var holiday;
while ((holiday = holidays[i++]) && holiday < endDate) {
if (startDate <= holiday) {
output.push(holiday)
}
}
return output;
}
If you are using ISO 8601 date strings, there's no need to convert them to Date objects. One of the reasons for the ISO format is that in most systems, you can compare strings directly rather than Date objects or some number value.
You can also parse the strings to Date objects, then use those to do the calculations but it takes more code for no real benefit:
// Parse date string in y-m-d format
function parseYMD(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[0], --b[1], b[2]);
return d.getFullYear() == b[0] && d.getDate() == b[2]? d : NaN;
}
// Holiday array
var holidays = ['2014-01-01','2014-07-04','2014-12-24', '2014-12-25'];
// Get holidays between two dates
function getHolidays(startDate, endDate) {
startDate = parseYMD(startDate);
endDate = parseYMD(endDate);
var output = [];
var i = 0;
var holiday;
for (var i=0, iLen=holidays.length; i<iLen; i++) {
holiday = parseYMD(holidays[i]);
if (holiday <= endDate) {
if (holiday >= startDate) {
output.push(holidays[i]);
}
}
}
return output;
}
console.log(getHolidays('2014-08-01', '2014-12-30')); // ["2014-12-24", "2014-12-25"]

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

Categories