I have two dates and want to save the days in between (plus start and end date) in an array
var date1 = new Date("Sep 23, 2013 12:00:00"); // Monday
var date2 = new Date("Sep 26, 2013 12:00:00"); // Thursday
var alldates = [];
for (var i=0; date1 <= date2; date1.setDate(date1.getDate() + 1), i++) {
alldates.push(date1);
}
alert(alldates.join('\n'));
With this code alert(alldates.join('\n')); shows the following
Fri Sep 27 2013 12:00:00 GMT+0200
Fri Sep 27 2013 12:00:00 GMT+0200
Fri Sep 27 2013 12:00:00 GMT+0200
Fri Sep 27 2013 12:00:00 GMT+0200
I am new to Javascript and want to get further understanding, so thank you for any explanation why the alert does not show
Mon Sep 23 2013 12:00:00 GMT+0200
Tue Sep 24 2013 12:00:00 GMT+0200
Wed Sep 25 2013 12:00:00 GMT+0200
Thu Sep 26 2013 12:00:00 GMT+0200
The problem you have is that you push references to the date1 object. When you change the date on it in your loop, you update the object, but all references still point to the same object.
You need to either push a text representation of your date, or a copy of your date1 object
for (var i=0; date1 <= date2; date1.setDate(date1.getDate() + 1), i++) {
alldates.push(new Date(date1));
}
alert(alldates.join('\n'));
As suggested, with a while loop
while( date1 <= date2 ) {
alldates.push(new Date(date1));
date1.setDate( date1.getDate() +1 );
}
Your array is storing the references for the single date object and everytime when setDate is called each of them are getting updated with new date value.
So it will be better to push the new date object in array like this,
var date1 = new Date("Sep 23, 2013 12:00:00"); // Monday
var date2 = new Date("Sep 26, 2013 12:00:00"); // Thursday
var alldates = [];
// pushing first date
alldates.push(new Date(date1.setDate(date1.getDate())));
for (var i=0; date1 <= date2; i++) {
alldates.push(new Date(date1.setDate(date1.getDate() + 1)));
}
alert(alldates.join('\n'));
To echo the other answers, the issue is that the element being pushed to the array isn't a value which stays the same - it refers to a Date object which changes in the loop, so all references to date1 stored in alldates are set to the final value of date1.
The accepted answer does the job, but it also mutates the value of date1. The OP set up the code with this side effect, which suggests that this isn't a problem for their use case. But if you'd prefer to not mutate date1, here's an alternative ES6-flavored, side effect-free approach:
const date1 = new Date("Sep 23, 2013 12:00:00"); // Monday
const date2 = new Date("Sep 26, 2013 12:00:00"); // Thursday
const msPerDay = 1000 * 60 * 60 * 24; // 86400000
const inclusiveDateLength = (date2 - date1) / msPerDay + 1; // 4
const allDates = Array.from(Array(inclusiveDateLength), (_, i) => {
const newDate = new Date(date1);
newDate.setDate(date1.getDate() + i);
return newDate;
});
console.log(allDates.join("\n"));
Explanation: We create an array, fill it new Dates, and increment the day of the month of each of those Dates with Date.prototype.setDate(). A cool feature of Array.from is that it accepts a map function as its second argument. We leverage the index value (i) in the map function to increment the day of the month of each date - note that this also works for wrap-arounds, such as Sep 29 to Oct 02.
When the Temporal API becomes available, it will probably offer a better solution to this problem.
Related
For m = range 1-12 it works as expected, increasing month by 1.
For m = range 13- it doesn't work as expected, increasing year by 1.
As m exceeds 12 inside loop I was expecting result:
Sun Feb 28 2015 00:00:00 GMT+0400 (GET)
Tue Mar 28 2015 00:00:00 GMT+0400 (GET)
Sat Apr 28 2015 00:00:00 GMT+0400 (GET)
Instead I get:
Sun Feb 28 2016 00:00:00 GMT+0400 (GET)
Tue Mar 28 2017 00:00:00 GMT+0400 (GET)
Sat Apr 28 2018 00:00:00 GMT+0400 (GET)
...
var loanAmount = 3800,
loanInterest = 32, // %
loanDuration = 48, // Month
loanGrace = 0,
loanFee = 1, // %
loanInitMonth = 0,
loanInitDay = 28,
loanInitYear = 2014;
var loanStart = new Date(loanInitYear,loanInitMonth,loanInitDay);
for (var m = loanInitMonth; m < loanDuration; m++) {
var d = loanStart;
d.setMonth(m);
console.log(m);
console.log(d);
}
Jsfiddle
As setMonth description states:
If a parameter you specify is outside of the expected range, setMonth
attempts to update the date information in the Date object
accordingly. For example, if you use 15 for monthValue, the year will
be incremented by 1 (year + 1), and 3 will be used for month.
I'm obviously not getting this behavior.
Browser Chrome.
When you do this, you are copying the reference to the Date object instead of creating a new copy of the object:
var d = loanStart;
Then, when you change the date in the d variable, you are also changing the date in the loanStart variable, as it's the same object.
Create a copy of the Date object:
var d = new Date(loanStart.getTime());
The problem is that you aren't adding the time to the original date, you're adding it to the current date. So setting the month > 12 to the current date will always add at least one year, which will increment the year.
You have two solutions:
Make sure you're always modifying the original date by maintaining a copy of that date.
Do real date math - trying to set the month (and rely on side-effects) when what you really want to do is increment the month makes for rather confusing code and will have edge cases when, for example, the day of the month isn't a valid day for that month.
Instead of passing m to setMonth, do d.setMonth(d.getMonth()+1) like below:
var loanAmount = 3800,
loanInterest = 32, // %
loanDuration = 48, // Month
loanGrace = 0,
loanFee = 1, // %
loanInitMonth = 0,
loanInitDay = 28,
loanInitYear = 2014;
var loanStart = new Date(loanInitYear,loanInitMonth,loanInitDay);
for (var m = loanInitMonth; m < loanDuration; m++) {
var d = loanStart;
d.setMonth(d.getMonth()+1);
console.log(m);
console.log(d);
}
This question already has answers here:
How to add days to Date?
(56 answers)
Closed 2 years ago.
I am trying to pull some historical data, which has a variety of time stamps. I want the use to a user selected date, and then pull all days + some additional days.
Date1 is
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1)
var Enddate = new Date();
Enddate.setDate(startDate + 10);
This doesn't work. I cant seem to figure out how to add the "10 days" to the Date1 variable.
You need the getDate function of the Date object, and you'll need to pass the correct value when instantiating the new Date.
Try this:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1);
// add it to startDate, using getDate()
startDate.setDate(startDate.getDate() + 10);
// now startDate will be 10 days later:
startDate; // Sun Nov 01 00:00:00 GMT-04:00 2020
// if you want an entirely new Date object, then instantiate a new one:
var Enddate = new Date(startDate);
If you want two different variables, then you can use the approach similar to what you tried, like so:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1), second = new Date(Date1); // we're using another temporary variable
// add the days
second.setDate(second.getDate() + 10);
// now use Enddate with this
var Enddate = new Date(second);
Enddate; // Sun Nov 01 00:00:00 GMT-04:00 2020
You can't just add a number to a Date object to get a new date.
You can add to a date by:
getting the current day of the month with getDate()
adding a number of days to that result
setting the new date with setDate()
const Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020";
const addDays = 10;
const startDate = new Date(Date1);
const startDays = startDate.getDate();
const newDate = new Date(startDate);
newDate.setDate(startDays + addDays);
console.log('startDate:', startDate.toISOString());
console.log('newDate:', newDate.toISOString());
Note:
Passing a string into the Date constructor is discouraged, as it produces inconsistent results across browsers.
It is better to pass in the individual date and time values:
const Date1 = new Date(2020, 9, 22, 0, 0, 0);
I am trying to create an object with all the dates from "today" until 60 days from now.
My code:
var dates = [];
getDateRange();
function getDateRange() {
var today = new Date();
var date = new Date();
for (var i = 0; i <= 59; i++) {
date.setDate(today.getDate()+i);
console.log(date);
dates[i] = date;
};
console.log(dates);
}
Prints out the dates correctly with the "console.log(date)" command, as follows:
Mon Jun 15 2015 21:31:47 GMT+0200
Tue Jun 16 2015 21:31:47 GMT+0200
Wed Jun 17 2015 21:31:47 GMT+0200
Thu Jun 18 2015 21:31:47 GMT+0200
Fri Jun 19 2015 21:31:47 GMT+0200
...
But once it is put into the dates array and printed out I get the following array of dates:
[Wed Jan 03 2024 21:42:47 GMT+0100,
Wed Jan 03 2024 21:42:47 GMT+0100,
Wed Jan 03 2024 21:42:47 GMT+0100,
Wed Jan 03 2024 21:42:47 GMT+0100,
...,
Wed Jan 03 2024 21:42:47 GMT+0100
]
I hope I explained the problem well.
The code is part of an AngularJS app but I think my problem has to do only with Javascript.
You need to reset the date, or they will be references of the same Date object.
var dates = [];
getDateRange();
function getDateRange() {
var today = new Date();
var date;
for (var i = 0; i <= 59; i++) {
date = new Date();
date.setDate(today.getDate() + i);
console.log(date);
dates.push(date);
};
console.log(dates);
}
In JavaScript, Date is a reference type. If you assign it to another var, the other var becomes a reference to the original date. So in this case, you end up with 59 pointers to the same date.
Solution: to actually makes copies of the date, you should clone it, by writing
dates[i] = new Date(date.getTime());
var dates = [];
getDateRange();
function getDateRange() {
var today = new Date();
var date = new Date();
for (var i = 0; i <= 59; i++) {
date.setDate(today.getDate()+i);
console.log(date);
dates[i] = new Date(date.getTime());
};
console.log(dates);
}
Try creating a new date every iteration instead of using the same date object:
function getDateRange() {
var today = new Date();
var date = new Date();
for (var i = 0; i <= 59; i++) {
var temp = new Date();
temp.setDate(today.getDate()+i);
console.log(temp);
dates[i] = temp;
};
console.log(dates);
}
In your case you were assigning the same date object to every location of the array and every time you update the date object all locations get updated because they all point to the same Date object.
You need to assign each member of your array to a unique new Date() instance.
In your example, the console.log() call correctly outputs the new time you've set date to in each iteration of the loop... but you're just changing the same Date object. Because every index of the array references the same Date object, they all point to the last set time (hence your problem).
I have two variables namely
date1 = Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
date2 = Mon Nov 25 2013 14:13:55 GMT+0530 (IST)
When I compare the two dates I get that date2 is greater which I need is correct. But I do not want to check the time part of the two dates I have. How could I get the date part alone from these two dates and compare it?
var today = new Date(); //Mon Nov 25 2013 14:13:55 GMT+0530 (IST)
d = new Date(my_value); //Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
if(d>=today){ //I need to check the date parts alone.
alert(d is greater than or equal to current date);
}
Try clearing the time using Date.setHours:
dateObj.setHours(hoursValue[, minutesValue[, secondsValue[, msValue]]])
Example Code:
var today = new Date();
today.setHours(0, 0, 0, 0);
d = new Date(my_value);
d.setHours(0, 0, 0, 0);
if(d >= today){
alert(d is greater than or equal to current date);
}
The best way would be to modify the accepted answer's if statement as follows
if(d.setHours(0,0,0,0) >= today.setHours(0,0,0,0))
In this way, you can easily check for equality as well because the return type for setHours() is integer.
Try:
var today = new Date(); //Mon Nov 25 2013 14:13:55 GMT+0530 (IST)
var d = new Date(my_value); //Mon Nov 25 2013 00:00:00 GMT+0530 (IST)
var todayDateOnly = new Date(today.getFullYear(),today.getMonth(),today.getDate()); //This will write a Date with time set to 00:00:00 so you kind of have date only
var dDateOnly = new Date(d.getFullYear(),d.getMonth(),d.getDate());
if(dDateOnly>=todayDateOnly){
alert(d is greater than or equal to current date);
}
var StartDate = $("#StartDate").val();
var EndDate = $("#EndDate").val();
if ((( EndDate - StartDate)/ (86400000*7))<0)
{
alert("Start Date Must Be Earlier Than End Date"); $("#StartDate").focus();
error = true;
return false;
}
I am trying to add two dates:
date start Fri Apr 26 2013 16:08:03 GMT+0100 (Paris, Madrid)
+
date periode Fri Apr 26 2013 00:10:00 GMT+0100 (Paris, Madrid)
I used this code:
var periode=$("#dure").val();
var start = $("#start").val()
var end =$("#end").val();
var dateStart= new Date(start);
console.log('start');
console.log(dateStart);
var date=dateStart.format('yyyy-mm-dd');
per=date+' '+periode;
var datePeriode= new Date(per);
console.log('datePeriode');
console.log(datePeriode);
var dateEnd= dateStart.getTime()+datePeriode.getTime();
console.log('dateEnd');
console.log(dateEnd);
In my JavaScript console, I get:
dateDebut
Fri Apr 26 2013 16:33:11 GMT+0100 (Paris, Madrid)
datePeriode
Fri Apr 26 2013 00:15:00 GMT+0100 (Paris, Madrid)
dateEnd
2733922091000
How can I fix that? Am I missing something?
If you want to add a time period to a date, you basically have to convert both of them into milliseconds.
var date = new Date();
var dateMillis = date.getTime();
//JavaScript doesn't have a "time period" object, so I'm assuming you get it as a string
var timePeriod = "00:15:00"; //I assume this is 15 minutes, so the format is HH:MM:SS
var parts = timePeriod.split(/:/);
var timePeriodMillis = (parseInt(parts[0], 10) * 60 * 60 * 1000) +
(parseInt(parts[1], 10) * 60 * 1000) +
(parseInt(parts[2], 10) * 1000);
var newDate = new Date();
newDate.setTime(dateMillis + timePeriodMillis);
console.log(date); //eg: Fri Apr 26 2013 08:52:50 GMT-0700 (MST)
console.log(newDate); //eg: Fri Apr 26 2013 09:07:50 GMT-0700 (MST)
Convert datePeriod to milliseconds instead of making it into a date object for your addition.
You need to convert the sum to a date. getTime() is in milliseconds since 1-1-1970. So you want to do.
var ending = new Date();
ending.setTime(dateEnd);
console.log(ending);
setTime will set the date properly for you.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/setTime