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).
Related
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 created a function to generate an array of dates arr in 1-month increments beginning at 1/1/2013 and going until now.
function getDateRange() {
var start = new Date('1/1/2013');
var today = new Date();
var arr = [start];
var next = new Date(start);
while (next < today) {
arr.push(next);
next = new Date(next.setMonth(next.getMonth() + 1));
}
Logger.log(arr);
Logger.log(arr.map(formatDate));
}
function formatDate(d) {
return Utilities.formatDate(d, 'MST', 'MMM-dd');
}
The function correctly generates arr, which looks like the following:
Jan 01 2013 00:00:00 GMT-0700 (MST),Fri Feb 01 2013 00:00:00 GMT-0700 (MST),Fri Mar 01 2013 00:00:00 GMT-0700 (MST),Mon Apr 01 2013 00:00:00 GMT-0600 (MDT),Wed May 01 2013 00:00:00 GMT-0600 (MDT)...
but then when I log arr.map(formatDate), I don't get the same dates starting at the 4th date:
Jan-01,Feb-01,Mar-01,Mar-31,Apr-30...
Any ideas why Utilities.formatDate is screwing up the dates?
function getDateRange() {
var start = new Date('1/1/2013');
var today = new Date();
var arr = [];
do {
arr.push(start);
start = new Date(start.setDate(start.getDate() + 1));
} while (start < today)
console.log(arr);
console.log(arr.map(formatDate));
}
function formatDate(date) {
return date.toLocaleString("en-us", {
month: "short",
timeZone: 'UTC'
}) + "-" + date.toLocaleString("en-us", {
day: "numeric",
timeZone: 'UTC'
});
}
I am displaying current day,month,date,year and time like this
Mon Oct 24 2016 17:09:25 GMT+0530 (India Standard Time)
but i need to display like this
Mon Oct 24 2016 17:09:25
my code in javascript:
var timestamp = new Date();
editor.insertHtml( 'The current date and time is: ' + timestamp.toString());
How can i do this please can anyone tell me how to do this.
Thank you
If you are open to add a library, you should use moment.js
console.log(moment().format('ddd MMM DD YYYY hh:mm:ss'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
If not, a small work around
var d = new Date().toString();
var index = d.lastIndexOf(':') +3
console.log(d.substring(0, index))
Note: moment approach is more preferred
var date = new Date();
var n = d.toLocaleString();
document.getElementById("demo").innerHTML = n;
This is work for me.
var timestamp = new Date();
console.log(
timestamp.toString().split('GMT')
)
// Mon Oct 25 2021 17:56:11 GMT+0530 (India Standard Time)`
the Output will be Mon Oct 25 2021 17:55:02
let today = new Date();
today = today.toString();
today = today.split('G')[0];
console.log(today);
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 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.