How to get the holidays date in my case? - javascript

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"]

Related

Expand date range using JS?

I have this variable {{ $daterange }} with json like this
{
"starts_at": "2020-05-20",
"ends_at": "2020-05-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
What I want to do is to expand something like this,
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
I'm planning to assign these dates inside of expandedDate variable
var expandedDate = [ ....dates ];
This should be done using jquery/js
UPDATE*
Recently this code works and can get all dates between 2 dates. It will list down all dates between 2 date range written in the code.
// Returns an array of dates between the two dates
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2013,10,22), new Date(2013,11,25));
dates.forEach(function(date) {
console.log(date);
});
How can I populate {{ $daterange }} contains multiple date range.
Think I missed your update with existing code. The following code seems to get the desired output using javascript. Just added comments to each step as an explanation. Hope it is helpful.
//sample input data
var daterange = [{
"starts_at": "2020-05-27",
"ends_at": "2020-06-23"
},
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth()+1 < 10 ? "0" + (date.getMonth()+1) : date.getMonth()+1;
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var from_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var to_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
// final result required
console.log(expandedDate);
Here's the complete code on how to solve this question
Based on #thommu
var daterange = [
{
"starts_at": "2020-05-24",
"ends_at": "2020-05-26"
},
{
"starts_at": "2020-05-27",
"ends_at": "2020-05-29"
}
];
// function to get dates between two dates
var getDaysAsArray = function(start_date, end_date) {
for (var arr = [], d = new Date(start_date); d <= end_date; d.setDate(d.getDate() + 1)) {
arr.push(new Date(d));
}
return arr;
};
// function to convert date into the format yyyy-mm-dd
var getFormattedDay = function(date) {
day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
month = date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
year = date.getFullYear();
return year + "-" + month + "-" + day;
}
//main logic
var expandedDate = [];
//Iterate through the list of arrays in the date range
for (var key in daterange) {
//get first pair of from and to date
var from_string = daterange[key].starts_at;
var to_string = daterange[key].ends_at;
// convert the string date to date format for from and to.
var xfrom_date = new Date(from_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
var xto_date = new Date(to_string.replace(/(\d{4})-(\d{2})-(\d{2})/, "$1/$2/$3"));
//Add +1 month to correct the data
var from_date = new Date(xfrom_date.setMonth(xfrom_date.getMonth()+1));
var to_date = new Date(xto_date.setMonth(xto_date.getMonth()+1));
// call getDaysAsArray to convert dates into strings and into an array.
var daylist = getDaysAsArray(from_date, to_date);
// iterate through the daylist and push it into the final array you want to use
for (var day in daylist) {
expandedDate.push(getFormattedDay(daylist[day]));
}
}
//Filter Duplicated Dates
var dateDuplicate = expandedDate;
var uniqueDate = [];
$.each(dateDuplicate, function(i, el){
if($.inArray(el, uniqueDate) === -1) uniqueDate.push(el);
});
// final result required
console.log(uniqueDate);

JavaScript for date range is only working with in a limit

I am trying to find the dates between two dates. I am attaching the script I have been using. It is working only if the start date and end date falls in between 4 months. If it is more than that it is failing.
Input I am passing ("01/01/2019","06/01/2019",1). What logic can I change here to get all the dates for larger date range.
WScript.StdOut.WriteLine(fnGetDateListInDateRange());
function fnGetDateListInDateRange() {
var addDays = WScript.Arguments.Item(2);
var startDate = WScript.Arguments.Item(0);
var endDate = WScript.Arguments.Item(1);
startDate = new Date(startDate);
endDate = new Date(endDate);
//
if (startDate > endDate)
{
return "-1";
}
//
var outputDate = new Array();
var tmpDate = new Date(startDate);
do {
outputDate.push(new Date(tmpDate));
tmpDate.setDate(tmpDate.getDate() + parseInt(addDays));
} while (tmpDate <= endDate);
//
return outputDate;
}

how to compare the current date with the input date in java script or jquery

I'm using cleandersonlobo:date-picker-materialize package to input the date and I want to display an alert("expired") if the input date is less than the current date.
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < new Date()) {
$('#myModal1').modal('hide');
alert("Job expired");
}
Try following code,
var $strDate = $(".pmt-date").val();
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
var $strToday = $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
if ($dtDate < $strToday ) {
$('#myModal1').modal('hide');
alert("Job expired");
}
A toMidnight function that sets the time of a date to midnight and by doing so removes time as a factor for your comparison:
function toMidnight(date) {
var midnight = arguments.length > 0 ? new Date(date) : new Date();
midnight.setHours(0);
midnight.setMinutes(0);
midnight.setSeconds(0);
midnight.setMilliseconds(0);
return midnight;
}
Then you can compare your date like this:
toMidnight($dtDate) < toMidnight()

Getting an array of days five days into the future fails

I am using moment js to get the date five days into the future with this code
//current date
var cd = moment().format("DD-MM-YYYY");
//5 days into the future
var nd = moment(cd, "DD-MM-YYYY").add(5, 'days').format('DD-MM-YYYY');
//get all dates from today to 5 days into the future
and now i am attempting to get an array of days between current date and the future date which is five days later
//current date
var cd = moment().format("DD-MM-YYYY");
//5 days into the future
var nd = moment(cd, "DD-MM-YYYY").add(5, 'days').format('DD-MM-YYYY');
//get all dates from today to 5 days into the future
console.log("start",cd);
console.log("end",nd);
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(cd, nd);
dates.forEach(function(date) {
console.log(date);
});
This is the demo https://jsfiddle.net/codebreaker87/z9d5Lusv/67/
The code only generates the current date. How can i generate an array of all dates between?.
If you are using momentjs already, then you seem to be doubling its functinality by your own code.
Consider the following snip:
var getDates = function( cd, nd ){
var dates = [];
var now = cd.clone();
for(var i = 0; i < nd.diff(cd, 'days') ; i++){
// format the date to any needed output format here
dates.push(now.add(i, 'days').format("DD-MM-YYYY"));
}
return dates;
}
var r = getDates( moment(), moment().add(10, 'days'));
// r now contains
["04-11-2016", "05-11-2016", "07-11-2016", "10-11-2016", "14-11-2016", "19-11-2016", "25-11-2016", "02-12-2016", "10-12-2016", "19-12-2016"]
I managed to solve it like this
//current date
var cd = moment().format("YYYY-MM-DD");
//5 days into the future
var nd = moment(cd, "YYYY-MM-DD").add(5, 'days').format('YYYY-MM-DD');
//get all dates from today to 5 days into the future
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
var dates = getDates(new Date(cd), new Date(nd));
dates.forEach(function(date) {
//format the date
var ald = moment(date).format("YYYY-MM-DD");
console.log(ald);
console.log(date);
});

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

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')
})

Categories