If date between date range - javascript

I'm working with two dates, e.g. 29/03/2014 and 04/04/2014, and I have an array of dates e.g. 01/04/2014 and 02/04/2014, I need to find out how many (if any) dates in that array are between the date range.
What's the best way to do this?
EDIT: Final code, tweaked a little from ponciste's answer
//date1 and date2 are the start/end dates
bhDays = new Array();
$.each(DataBridge.bankHolidays, function(i, v) {
var americanDate = v.split('-');
americanDate = americanDate[1] + '/' + americanDate[0] + '/' + americanDate[2];
date = new Date(americanDate);
if (date1 <= date && date2 >= date) {
bhDays.push(date);
}
});

it's better to deal with Date object in this case
so your code should be something like this:
var strDateFrom = "29/03/2014";
var strDateTo = "04/04/2014";
var dateFrom = strDateFrom.split("/");
var dateTo = strDateTo.split("/");
var dates = ["01/04/2014", "02/04/2014"];
var from = new Date(dateFrom[2], dateFrom[1]-1, dateFrom[0]);
var to = new Date(dateTo[2], dateTo[1]-1, dateTo[0]);
dates.forEach(function(date) {
var dateToCheck = new Date(date[2], date[1]-1, date[0]);
if(dateToCheck > from && dateToCheck < to)
});

The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
Construct your date objects and compare using < || > operators.

I strongly reccoment to use moment.js library for that (and all other operations with date/time) and use difference function.

Related

Get dates list between 2 dates (fromDate and toDate) in utc time using angular7

I have try to get dates list between two date using JavaScript (I have already achieved in GMT).
Example:
fromDate - 2019-08-27
toDate - 2019-08-30
Date list
[2019-08-27, 2019-08-28, 2019-08-29, 2019-08-30]
I have already got this array using this following JavaScript
if(result.data.closurPeriods.length > 0) {
result.data.closurPeriods.forEach(closure => {
var start = closure.fromDate, //closure.fromDate = 2019-08-27
end = new Date(closure.toDate), //closure.toDate = 2019-08-30
currentDate = new Date(start);
while (currentDate <= end) {
this.closurPeriods.push(this.datePipe.transform(new Date(currentDate), 'yyyy-MM-dd'));
currentDate.setDate(currentDate.getDate() + 1);
}
});
}
The above JavaScript is working for only GTM and localtime(India). When I try to run this script in USA the date list array like this
[2019-08-28, 2019-08-28, 2019-08-29]
Because of UTC not accept this script.
My question is how to solve this above script in UTC
2019-08-27 is parsed as UTC, but getDate and setDate are local. The USA is west of Greenwich, so new Date('2019-08-27') produces a local date for 2019-08-26, adding a day makes it 2019-08-27.
The same thing will happen for any timezone that has a negative offset.
A simple fix is to use all UTC, e.g.:
function fillRange(start, end) {
let result = [start];
let a = new Date(start);
let b = new Date(end);
while (a < b) {
a.setUTCDate(a.getUTCDate() + 1);
result.push(a.toISOString().substr(0,10));
}
return result;
}
let from = '2019-08-27';
let to = '2019-08-30';
console.log(fillRange(from, to));
However, I'd advise explicitly parsing the date and not to use the built–in parser. A simple parse function is 2 or 3 lines of code, or you can use one of many parsing and formatting libraries.
Finally i got the solutions
var start = new Date(closure.fromDate); // 2019-07-27
var end = new Date(closure.toDate); // 2019-07-31
var currentDate = start;
while (currentDate <= end) {
//this.closurPeriods.push(this.datePipe.transform(new Date(currentDate), 'yyyy-MM-dd'));
var date = new Date(currentDate);
var datewithouttimezone = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
this.closurPeriods.push(this.datePipe.transform(new Date(datewithouttimezone), 'yyyy-MM-dd'));
currentDate.setDate(currentDate.getDate() + 1);
}
Or
var start = new Date(closure.fromDate); // 2019-07-27
var end = new Date(closure.toDate); // 2019-07-31
var currentDate = start;
while (start < end) {
start.setUTCDate(start.getUTCDate() + 1);
this.closurPeriods.push(start.toISOString().substr(0, 10));
}

Find if date is the next valid date from today Momentjs

This is a straight question but I don't find any suitable solution. Given an array of dates, ie
['2015-01-01', '2015-04-20', ...]
Is there any way to check if a item of the array is the next valid date after today?
I am using moment.js.
[…] Is there any way to check if a item of the array is the next valid date after today?
Your description is not really clear to me, but it sounds like you’re trying to programmatically determine if an array of dates contains tomorrow’s date (i.e. “the next valid date after today”). In that case, read on:
First, get tomorrow’s date in the same format as the strings in your array using moment.js:
var tomorrow = moment().add(1, 'days').format('YYYY-MM-DD');
Now you can just loop over the array and compare each value to tomorrow using == or === (doesn’t matter in this case):
dates.forEach(function(date) {
if (date == tomorrow) {
// Bingo!
}
});
If you just want to check if any of the dates in the array are tomorrow’s date, use Array#some:
var containsTomorrow = dates.some(function(date) {
return date == tomorrow;
});
This can actually be solved without using momentjs
var todaysDate = new Date();
var min;
var index;
var array = ['2015-01-01', '2015-04-20', ...];
for (var i = 0; i < array.length; i++) {
var inputDate = new Date(array[i]);
var ts = inputDate - todaysDate;
if (!min || (ts < min && ts > 0) ) {
min = ts;
index = i;
}
}
// index will contain the index of the nearest next date

How to filter the data using date from JSON format

I want to filter using date but the data is in JSON format. How can I filter the large dataset using date in JavaScript?
Example:
data=[{date:'22-12-2014',name:'selva'},{date:'10-10-2010',name:'raja'},{date:'11-11- 2011',name:'suresh'}]
If you simply want to filter data by time, you can look through all objects in the array like this:
var filteredData = [];
for(var index in data) {
var obj = data[index];
var date = parseDate(obj.date);
//Filter dates from 2011 and newer
if(date > new Date(2011, 0, 1))
filteredData.push(obj);
}
function parseDate(dateStr) {
var date = dateStr.split('-');
var day = date[0];
var month = date[1] - 1; //January = 0
var year = date[2];
return new Date(year, month, day);
}
//Filtered data now contains:
// [{"date":"22-12-2014","name":"selva"},{"date":"11-11- 2011","name":"suresh"}]
I am sure you could do the parse date better, by for example defining the date in a format that the Date constructor accepts.
To grab the set of elements that match a certain date you can use filter to extract them into a new array.
function getByDate(date){
return data.filter(function (el) {
return el.date == date;
});
}
var arr = getByDate('11-11-2011');
To to sort your dataset by date you need to convert your date strings to a JS date object first. That involves adjusting the date string slightly so it can be parsed properly.
function reformatDate(date) {
return arr = date.split('-').reverse();
}
var sortByDate = function (a, b) {
return new Date(reformatDate(a.date)) - new Date(reformatDate(b.date));
};
data.sort(sortByDate);
JSFiddle demo
I used date format MM/DD/YY. Here is the full example -
var data=[
{date:'02/10/2018',name:'date is 10'},
{date:'02/14/2018',name:'date is 14'},
{date:'02/16/2018',name:'date is 16'},
{date:'02/20/2018',name:'date is 20'},
{date:'02/24/2018',name:'date is 24'},
{date:'02/26/2018',name:'date is 26'},
{date:'02/30/2018',name:'date is 30'},
{date:'03/01/2018',name:'date is 01'},
{date:'03/05/2018',name:'date is 05'},
{date:'02/23/2018',name:'date is name 23'},
]
var today = new Date();
var todayTime = new Date().getTime();
var days_after_20 = new Date().setDate(today.getDate()+20);
var days_before_5 = new Date().setDate(today.getDate()-5);
var result = data.filter(function (item) {
var itemTime = new Date(item.date).getTime()
return itemTime >= days_before_5 && itemTime <= days_after_20;
})
console.log(result);
To fetch the set of elements that match a certain date you can use filter to extract them into a new array.
var tempArray= data.filter(function (d, i) {
return d >= startDate && d <= endDate;
})

comparing dates in JavaScript using moment with langs

I have two dates namely newdate and haha. newdate will be today's date (current date) and haha date can be any.The below code is not working for me as i have provided
newdate : 07-Feb-2014 10:04
haha :03-Feb-2014 00:00
its always coming to else part
sdate:03-Feb-2014
stime :00:00
var haha=sdate+" "+stime;
var newdate=new Date();
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
alert(date_str);
if (Date.parse(haha) < Date.parse(date_str)) {
alert("Start date cannot be less than today's date");
return false;
}
else {
alert("hahahhahaha");
}
NOTE I am using moment with langs javscript
Your Code Works. Stime is formatted wrong remove the colon from in front of the first set of 00. stime 00:00. How are you generating stime this is the cause of you problem?
You can see my test here.
var sdate = "03-Feb-2014";
var stime = "00:00";
var haha = sdate + " " + stime;
var newdate = new Date();
if (navigator.appName.indexOf("Internet Explorer") != -1) {
alert("isIE");
var dateObject = (parseISO8601(haha));
var hahaDate = new Date(dateObject.year, dateObject.month, dateObject.day, dateObject.hour, dateObject.min);
alert(hahaDate);
if (hahaDate.getTime() < newdate.getTime()) {
alert("Start date cannot be less than today's date");
return false;
} else {
alert("hahahhahaha");
}
} else {
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
alert(date_str);
if (Date.parse(haha) < Date.parse(date_str)) {
alert("Start date cannot be less than today's date");
return false;
} else {
alert("hahahhahaha");
}
}
function parseISO8601(dateStringInRange) {
var dateAsObject = {};
var splitTimeFromDate = dateStringInRange.split(" ");
var splitTimeValues = splitTimeFromDate[1].split(":");
dateAsObject.hour = splitTimeValues[0];
dateAsObject.min = splitTimeValues[1];
var splitDate = splitTimeFromDate[0].split("-");
dateAsObject.year = splitDate[2];
dateAsObject.day = splitDate[0];
dateAsObject.month = monthToNum(splitDate[1]);
return dateAsObject;
}
function monthToNum(month) {
if (month == "Feb") return 1;
}
[Edit: Ok sorry I messed up with the Colon, If it fails at the else are you sure you unit tests include enough scenario to were the date is both greater than and less than the current date if it is only less than like your example you will never hit the code in the else. Again the code just works don't know what to say :-(, update example for both situations]
[Edit: Here is an example not complete you have to remember javascript is not universal. When you ask a question about JS assume as DEVs we all use Chrome or FF, or atleast post the browser(s) you tired. I provided a simple example of how I would accomplish this. Frankly I don't like external framework when I can do it myself so as you can see I am not using it feel free to do what you want the issue is cause by the way IE Parses DateTime you must use a more universal format like the one provided below. Example of possible formats: http://www.w3schools.com/jsref/jsref_obj_date.asp. Anyhow GL]
That is a bit convoluted, consider:
var newdate = new Date();
var date_str = moment(newdate).format("DD-MMM-YYYY HH:mm");
Date.parse(date_str);
if the above works (and there is absolutely no guarantee that Date.parse will correctly parse the string in all browsers in use), then all of that is equivalent to:
var newdate = new Date();
newdate.setSeconds(0, 0);
You would do very much better to manualy parse haha (or use moment.js since you have it already) and compare the resultant date objects.
Consider:
// s is dd-mmm-yyyy hh:mm
function stringToDate(s) {
s = s.split(/[- :]/);
var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun': 5,
'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11};
return new Date(s[2], months[s[1].toLowerCase()], s[0], s[3], s[4], 0, 0);
}
var newdate = '07-Feb-2014 10:04';
var haha = '03-Feb-2014 00:00';
alert(stringToDate(newdate).getTime() == stringToDate(haha).getTime()); // false
// Set to same time
var newdate = '03-Feb-2014 00:00';
alert(stringToDate(newdate).getTime() == stringToDate(haha).getTime()); // true

Check the dates in JavaScript

I want to check two dates in java script. date format is YYYY-MM-dd.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I write condition?
If you mean that you want to compare them and your variables are strings, just use == for comparison.
var date1 = '1990-26-01';
var date2 = '2000-01-05';
if (date1 == date2) {
alert('date1 = date2')
}
else {
alert('something went wrong');
}
There are four ways of instantiating dates
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Here is the link to complete tutorial and function of creating, comparing dates http://www.w3schools.com/js/js_obj_date.asp
If you want to compare dates , have a look at the JS date object https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date , in particular the getTime() method .
Assuming the format is YYYY-MM-dd (your second date value breaks this rule) and that they are strings...
var date1 = '2011-9-2';
var date2 = '2011-06-17';
var fields = date1.split("-");
var d1 = new Date (fields[0], fields[1]-1, fields[2]);
var fields = date2.split("-");
var d2 = new Date (fields[0], fields[1]-1, fields[2]);

Categories

Resources