Date object doesn't exist after definition? - javascript

I'm trying to make a function that returns an array of dates in between two dates. This is my code:
Date.prototype.addDays = function(days)
{
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getdaterange(startdate, enddate)
{
var s = new Date(startdate);
var e = new Date(enddate);
var datearray = [s];
var done = false;
while(!done)
{
var date = datearray.pop().addDays(1);
if (date == e)
{
datearray.push(date);
done = true;
}
}
}
getdaterange("2018-09-01", "2018-09-25");
The function isn't done yet, but when I try to manipulate the date object on the line that sets the variable "date", it comes back as undefined or says that .pop() isn't a method of Date. I've tried several different configurations. (Where I change how I am manipulating the date object. For example: defining the variable and then calling the .addDays() method afterwards.)
This is just one of them. Does anybody know whats going on?
Thanks for any help in advanced.
Thanks for your help from the comments. Edited Code:
Date.prototype.addDays = function(days)
{
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getdaterange(startdate, enddate)
{
var s = new Date(startdate);
var e = new Date(enddate);
var datearray = [s];
var done = false;
while(!done)
{
var temp = datearray;
var date = temp.pop().addDays(1);
if (date.valueOf() == e.valueOf())
{
datearray.push(date);
done = true;
}
else
{
datearray.push(date);
}
}
return datearray;
}
console.log(getdaterange("2018-09-01", "2018-09-25"));

Rather than trying to 'extend' the Date class, you can encapsulate the desired logic in it's own class as follows
class DateUtil {
static addDays(date, days) {
return date.setDate(date.getDate() + days)
}
static getDateRange(dateStart, dateEnd) {
let date = new Date(dateStart);
let endDate = new Date(dateEnd);
let dates = [];
while (date < endDate) {
dates.push(new Date(this.addDays(date, 1)))
}
return dates;
}
}
DateUtil.getDateRange('2018-09-01', '2018-09-25')
.forEach(date => console.log(date.toString()));

What I ended up needing to do (after fixing the first problem) was set var temp equal to var datearray through a method like Array.from(). That way temp wasn't pointing to datearray directly and I always ended up with one item in the array.
Date.prototype.addDays = function(days)
{
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function getdaterange(startdate, enddate)
{
var s = new Date(startdate);
var e = new Date(enddate);
var datearray = [s];
var done = false;
while(!done)
{
var temp = Array.from(datearray);
var date = temp.pop().addDays(1);
if (date.valueOf() == e.valueOf())
{
datearray.push(date);
done = true;
}
else
{
datearray.push(date);
}
}
return datearray;
}

Related

Remove specific dates from array

I got an array, which contains dates (formatted as dates, not strings) within a specified range:
var dates = 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 startDate = new Date("2019-04-01");
var endDate = new Date("2019-04-26");
var dates = dates(startDate, endDate);
Then I filtered out the weekends like this:
var workingDays = dates.filter(function(e, index){
return (e.getDay() != 0 && e.getDay() != 6);
});
That worked perfectly so far, but my problem is that I need to filter out holidays aswell. I tried to use the same filter function as for the weekends, like this:
var holidays = [new Date("2019-04-19"), new Date("2019-04-22")];
var workingDays = dates.filter(function(e, index){
return (e.getDay() != 0 && e.getDay() != 6 && e != holidays);
});
That didn't work tho and just returned the same array as before.
Does anyone know how I can achieve this and just filter out the specified dates in the variable?
var holidays = [new Date("2019-04-19").toString(), new Date("2019-04-22").toString()];
var dates = [new Date("2019-04-19"), new Date("2019-04-22"), new Date("2019-01-21")];
var workingDays = dates.filter(function(e, index){
return (e.getDay() != 0 && e.getDay() != 6 && holidays.indexOf(e.toString()) === -1);
});
console.log(workingDays)
Since dates are objects we need some unique property we can check them on. In this case you could try the following. But I am sure there are some more optimized and elegant solutions
Since we cannot compare two Date objects, we can compare instead their ms timestamp counterparts like:
!holidays.some(d => +d === +e)
where +d and +e is a shorthand for new Date().getTime()
Example:
var dates = 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 startDate = new Date("2019-04-01");
var endDate = new Date("2019-04-26");
var dates = dates(startDate, endDate);
var holidays = [new Date("2019-04-19"), new Date("2019-04-22")];
var workingDays = dates.filter(function(e, index){
return (e.getDay() != 0 && e.getDay() != 6 && !holidays.some(d => +d === +e));
});
console.log(workingDays)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Change e != holidays to !holidays.some( x => +x=== +e )
Explanation: +x is shortcut for call x.getTime() for compare dates timestamp.
var dates = 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 startDate = new Date("2019-04-01");
var endDate = new Date("2019-04-26");
var dates = dates(startDate, endDate);
var holidays = [new Date("2019-04-19"), new Date("2019-04-22")];
var workingDays = dates.filter(function(e, index){
return (e.getDay() != 0 && e.getDay() != 6 && !holidays.some(x=>+x===+e));
});
console.log(workingDays);

How to get dates array between two date time

I have a following date fields
{ tripScheduleStartDate: '2018-12-05T18:30:00.000Z',
tripScheduleEndDate: '2018-12-07T18:30:00.000Z',
}
How can i get datetime array from start to end, something like this
[ { date: '2018-12-05T18:30:00.000Z' }, { date: '2018-12-06T18:30:00.000Z' },{ date: '2018-12-07T18:30:00.000Z' } ]
PSEUDO-CODE
Time start = x;
Time end = y
tmpTime = x;
timeArray = [];
While (tmpTime < y) {
timeArray.Add(tmpTime)
tmpTime = tmpTime.AddDays(1);
}
You could use eachDay from date-fns.
{
tripScheduleStartDate: '2018-12-05T18:30:00.000Z',
tripScheduleEndDate: '2018-12-07T18:30:00.000Z',
}
Import: import eachDay from 'date-fns/each_day'
Usage: eachDay(tripScheduleStartDate, tripScheduleEndDate)
This may help you
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
function gettheDates(sDate, eDate) {
var dateArray = new Array();
var ctDate = sDate;
while (ctDate <= eDate) {
dateArray.push(new Date (ctDate ));
ctDate = ctDate .addDays(1);
}
return dateArray;
}

How to return an array of all the dates between two selected dates using javascript

For my class assignment, I need to return an array of dates in between two selected dates on a calendar (arrival & departure).
I was given two sets of code that I can use, however I can't figure out how to link them together.
var arrival = document.getElementById('arrivalDate');
console.log(arrival.value);
var checkout = document.getElementById('departureDate');
console.log(checkout.value);
// Figure out the number of days they are check in for.
var days = checkout.value.split('-')[2] - arrival.value.split('-')[2];
console.log(days);
function dateRange(arrival, days) {
range = [];
// Starting At
return range;
}
// 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);
});
Seems pretty simple when you've already been given the answer!
var arrivalDate = new Date(document.getElementById('arrivalDate').value);
var departureDate = new Date(document.getElementById('departureDate').value);
var dateRange = getDates(arrivalDate, departureDate);

Check if date is in the past Javascript

All,
I'm using the jQuery UI for the date picker. I'm trying to check with javascript though that the date the user has entered is in the past. Here is my form code:
<input type="text" id="datepicker" name="event_date" class="datepicker">
Then how would I check this with Javascript to make sure it isn't a date in the past? Thanks
$('#datepicker').datepicker().change(evt => {
var selectedDate = $('#datepicker').datepicker('getDate');
var now = new Date();
now.setHours(0,0,0,0);
if (selectedDate < now) {
console.log("Selected date is in the past");
} else {
console.log("Selected date is NOT in the past");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input type="text" id="datepicker" name="event_date" class="datepicker">
var datep = $('#datepicker').val();
if(Date.parse(datep)-Date.parse(new Date())<0)
{
// do something
}
To make the answer more re-usable for things other than just the datepicker change function you can create a prototype to handle this for you.
// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
if (!this.prototype[name]) {
this.prototype[name] = func;
return this;
}
};
Date.method('inPast', function () {
return this < new Date($.now());// the $.now() requires jQuery
});
// including this prototype as using in example
Date.method('addDays', function (days) {
var date = new Date(this);
date.setDate(date.getDate() + (days));
return date;
});
If you dont like the safety check you can use the conventional way to define prototypes:
Date.prototype.inPast = function(){
return this < new Date($.now());// the $.now() requires jQuery
}
Example Usage
var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());
Simply convert the dates into milliseconds and subtract
let givenDate1 = new Date("10/21/2001") // Past Date
let givenDate2 = new Date("10/21/2050") // future Date
If diff is positive, then given date is PAST
let diff = new Date().getTime() - givenDate1.getTime();
if (diff > 0) {
console.log('Given Date givenDate1 is in Past');
}
If diff is negative, then given date is Future
let diff = new Date().getTime() - givenDate2.getTime();
if (diff < 0) {
console.log('Given Date givenDate2 is in Future');
}
You can use isPast(date) method from date-fns library.
import { isPast } from 'date-fns'
console.log(new Date('1991-06-17'));
// returns true.
console.log(new Date('2191-06-17'));
// returns false.
More info about the method:
https://date-fns.org/v2.29.3/docs/isPast
function isPrevDate() {
alert("startDate is " + Startdate);
if(Startdate.length != 0 && Startdate !='') {
var start_date = Startdate.split('-');
alert("Input date: "+ start_date);
start_date=start_date[1]+"/"+start_date[2]+"/"+start_date[0];
alert("start date arrray format " + start_date);
var a = new Date(start_date);
//alert("The date is a" +a);
var today = new Date();
var day = today.getDate();
var mon = today.getMonth()+1;
var year = today.getFullYear();
today = (mon+"/"+day+"/"+year);
//alert(today);
var today = new Date(today);
alert("Today: "+today.getTime());
alert("a : "+a.getTime());
if(today.getTime() > a.getTime() )
{
alert("Please select Start date in range");
return false;
} else {
return true;
}
}
}

javascript check end date is greater than or equal to start date

Is it possible to check whether an end date is greater than or equal to a start date in Javascript? My dates are strings in the format 'dd/mm/yyyy'.
try this
var startDate = "05/01/2011";
var endDate = "09/01/2011";
var regExp = /(\d{1,2})\/(\d{1,2})\/(\d{2,4})/;
if(parseInt(endDate.replace(regExp, "$3$2$1")) > parseInt(startDate.replace(regExp, "$3$2$1"))){
alert("greater");
}
If the string format ('dd/mm/yyyy') doesn't change, this function should work:
function endAfterStart(start,end){
return new Date(start.split('/').reverse().join('/')) <
new Date(end.split('/').reverse().join('/'));
}
alert(endAfterStart('05/01/2011','09/01/2011')); //=> true
Or extend the Date.prototype:
Date.prototype.isBefore = Date.prototype.isBefore || function(dat){
return this < dat;
}
new Date('05/01/2011'.split('/').reverse().join('/'))
.before( new Date('09/01/2011'.split('/').reverse().join('/')) ); //=>true
Most simple way to do this.
function endAfterStart(start, end) {
var startDate = new Date(start);
var endDate = new Date(end);
return endDate.getTime() >= startDate.getTime();
}
function isDate(value)
{
var fromDate = document.getElementById("fromDate").value
var toDate= document.getElementById("toDate").value
//var curr_Date= new SimpleDateFormat("dd/mm/yyyy");
var dateRegEx = null;
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if (dateRegEx.test(fromDate)){
}
else{
alert("Invalid from date");
return false;
}
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if(dateRegEx.test(toDate)) {
}
else{
alert("Invalid to date");
return false;
}
var stDate = new Date(fromDate);
var enDate = new Date(toDate);
var compDate = enDate - stDate;
//var fdate=enDate-curr_Date;
if(compDate >= 0)
return true;
else
{
alert("To Date cannot be smaller than From Date");
return false;
}
/**/
}
This will work for Leap years also..in dd/mm/yyyy format(not any other format).
Took me some time to find, but JQuery implements this exact functionality with DatePicker date-range. (Source code available in link as well.)
Moment.js also handles date comparisons very well using the diff function.
check out this function
function CompareDates()
{
var str1 = document.getElementById("Fromdate").value;
var str2 = document.getElementById("Todate").value;
var dt1 = parseInt(str1.substring(0,2),10);
var mon1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var dt2 = parseInt(str2.substring(0,2),10);
var mon2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 < date1)
{
alert("To date cannot be greater than from date");
return false;
}
else
{
alert("Submitting ...");
document.form1.submit();
}
}
Try this,
function isDateCompare(){
var leadDate = document.getElementById('strDate').value;
var closeDate = document.getElementById('strDateClosed').value;
var date1 = new Date();
date1.setFullYear(leadDate.substr(6,4),(leadDate.substr(3,2)-1),leadDate.substr(0,2));
var date2 = new Date();
date2.setFullYear(closeDate.substr(6,4),(closeDate.substr(3,2)-1),closeDate.substr(0,2));
if (date1> date2)
{
alert("Expected Closed date cannot be less than Lead date.");
return false;
}
else
{
alert("true");
return false;
}
}
First use this function will convert string to Date type in js:
function common_getDateFromUI(str) {
var arr = str.split("/");
var returnDate = new Date(arr[2], arr[1] - 1, arr[0], 0, 0, 0, 0);
return returnDate;
}
Second: after you get the javascript date type, you just compare it as normal type like date1 > date2 or date1 == date2.
Or use this function to get the difference date between date:
function CalendarDays(startDate, endDate) {
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.round(diff / millisecondsPerDay);
return days;
}
Follow this link is a simple demo to get difference days between dates. Link demo here
if (iForm.DiddfromDate.value == "")
{
alert(" Please enter a value");
iForm.DiddfromDate.focus();
return false;
}
if (iForm.DiddtoDate.value == "")
{
alert(" Please enter a value");
iForm.DiddtoDate.focus();
return false;
}
try {
var d1 = iForm.DiddfromDate.value.substr(0, 2);
var m1 = iForm.DiddfromDate.value.substr(3, 2);
var y1 = iForm.DiddfromDate.value.substr(6, 4);
var StrDate = m1 + "/" + d1 + "/" + y1;
var d2 = iForm.DiddtoDate.value.substr(0, 2);
var m2 = iForm.DiddtoDate.value.substr(3, 2);
var y2 = iForm.DiddtoDate.value.substr(6, 4);
var EndDate = m2 + "/" + d2 + "/" + y2;
var startDate = new Date(StrDate);
var endDate = new Date(EndDate);
if (startDate > endDate) {
alert('To date should be greater than From date.');
iForm.DiddfromDate.value = '';
iForm.DiddtoDate.value = '';
iForm.DiddfromDate.focus();
return false;
}
} catch (e) { alert(e.Description); }
return true;
Just convert the string to date and use getTime method of Date object to compare it.
Example code
var startDate = '04/04/2015'; //date in dd/mm/yyyy format
var endDate = '05/04/2015';
function compareDates(sDate, eDate) {
var dateTime1 = new Date(sDate).getTime(),
dateTime2 = new Date(eDate).getTime();
var diff = dateTime2 - dateTime1;
if (diff > 0) {
alert("endDate is greater than startDate");
return true;
}
}
compareDates(startDate, endDate);
Working Fiddle

Categories

Resources