JS : add date obgectto array - javascript

i try to make array of dates ,but when i push the last one all the other dates in the array be the same last one .
var dateArayy=[];
var date = new Date();
function addone(){
date.setDate(date.getDate()+1); //add day to the date
dateArayy.push(date) ;
// i try also dateArayy[dateArayy.lenght]=date THE SAME..
}
for (let i=1;i<10;i++){
addone();
}
console.log(dateArayy)

you change and set the same object in array . you should create new Date object and add it to the array
var dateArayy = [];
var date = new Date();
function addone() {
var newdate = new Date();
newdate.setDate(date.getDate() + 1);
date = newdate;
dateArayy.push(date);
}
for (let i = 1; i < 10; i++) {
addone();
}
console.log(dateArayy);

let dates = [];
for (let i = 0; i < 10; i++) {
let date = new Date();
date.setDate(date.getDate() + i);
dates.push(date);
}
console.log(dates);

Related

How to get next date time start from 12:00:00 in javascript

Here I'm looping the date to get past 50 days date!!
but the problem is I only want the current date time as the current time and next from there all date time I want as 12:00:00 !!
const dates = [];
const today = dayjs(new Date());
for (let d = 0; d < 50; d++) {
dates.push(today.subtract(d, "day"));
}
console.log(dates);
const dates = [];
for (let d = 0; d < 50; d++) {
const date = new Date()
if (d !== 0) {
date.setHours(12, 0, 0)
}
dates.push(date)
}
console.log(dates);
const dates = [];
const date = new Date();
for (let i = 0; i < 50; i++) {
var currentDate = new Date();
if (i !== 0) {
currentDate.setDate(currentDate.getDate() + i);
currentDate.setHours(12, 0, 0);
}
dates.push(currentDate);
}
console.log(dates);

Javascript Date object funny behavior with .toLocaleDateString()

Sorry if this is a newbie question... I have this working correctly:
let date = new Date(2021, 0, 12);
dates = [];
for (let i = 0; i < 30; i++) {
date.setDate(date.getDate() + 1);
const dateString = date.toLocaleDateString();
dates.push(dateString);
}
console.log(dates);
All good. But without the new variable 'dateString', I see a funny behavior I don't quite understand. Initially I tried to do:
let date = new Date(2021, 0, 12);
let dates = [];
for (let i = 0; i < 30; i++) {
date.setDate(date.getDate() + 1);
date = date.toLocaleDateString(); // change same var instead of new var
dates.push(date);
}
console.log(dates);
This throws the following error: TypeError: date.getDate is not a function. Why should the behavior of the date object change in reverse?

show 2 week in the past ( vue.js)

Hi i have this script ( vue.js ) i can see the next 2 weeks works good i must change that i can see 2 weeks on the past ..
Thanks
methods: {
// Get all days without sunday:
dates(index) {
var week = new Array();
let current = new Date();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 13; i++) {
let date = new Date(current);
week.push(moment(date).format('DD.MM.YY'));
current.setDate(current.getDate() +1);
}
return week[index];
},
If you want to go back in time, you need to subtract from the current date:
methods: {
// Get all days without sunday:
dates(index) {
var week = new Array();
let current = new Date();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 13; i++) {
let date = new Date(current);
week.push(moment(date).format('DD.MM.YY'));
current.setDate(current.getDate() - 1); // <-- this line changed
}
return week[index];
},
Try this:
function dates(index) {
var week = new Array();
let current = moment().subtract(1, 'days');
for (var i = 0; i < 12; i++) {
week.push(current.format('DD.MM.YY'));
current = current.subtract(1, 'days')
}
console.log(week);
return week[index];
}
console.log(dates(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

Calculating array of dates

I'm trying to convert an array of days:
['1','2','3','4','5']
to an array of dates which are today +1 day , today +2 etc
I have:
interval_dates = []
var intervals = rows[index+1][0].split(',')
var now = new Date();
for (i in intervals){
// add a day
interval_dates.push(now.setDate(now.getDate() + intervals[i]));
}
Logger.log(interval_dates);
I'm seeing
[1.505998326018E12, 1.522500726018E12, 1.546869126018E12, 1.552654326018E12, 1.564750326018E12], ]
what am I doing wrong?
var dateRange = [];
['1','2','3','4','5'].forEach(function(dayIncrement) {
var date = new Date();
date.setDate(date.getDate() + parseInt(dayIncrement));
dateRange.push(date);
});
console.log(dateRange);
The intervals are string, you need to get the day of today and add the interval after converting it to a number using +interval, so it would be now.getDate() + +intervals[i], then call new Date() on the result, and of course change the loop from i in intervals to a number range:
var intervals = ['1','2','3','4','5'];
var interval_dates = [];
var date;
for (var i=0; i<intervals.length; i++){
// add a day
date = new Date();
interval_dates.push(new Date(date.setDate(date.getDate() + +intervals[i])));
}
console.log(interval_dates);
function arrayOfDays()
{
var dayA=[1,2,3,4,5];
var today=new Date().setHours(0,0,0,0);
var day=24*60*60*1000;
var days=[];
for(var i=0;i<dayA.length;i++)
{
days.push(Utilities.formatDate(new Date(today + (i * day)), Session.getScriptTimeZone(), "MM/dd/yyyy"));
}
//Logger.log(days);
var ui=HtmlService.createHtmlOutput('[' + days.join(', ') + ']');
SpreadsheetApp.getUi().showModelessDialog(ui, 'Array of Days')
}

Get a list of dates between two dates using javascript

From JavaScript is there a way to get list of days between two dates from MySQL format. I don't want to use any library for this.
This is what i did.
function generateDateList(from, to) {
var getDate = function(date) { //Mysql Format
var m = date.getMonth(), d = date.getDate();
return date.getFullYear() + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
}
var fs = from.split('-'), startDate = new Date(fs[0], fs[1], fs[2]), result = [getDate(startDate)], start = startDate.getTime(), ts, end;
if ( typeof to == 'undefined') {
end = new Date().getTime();
} else {
ts = to.split('-');
end = new Date(ts[0], ts[1], ts[2]).getTime();
}
while (start < end) {
start += 86400000;
startDate.setTime(start);
result.push(getDate(startDate));
}
return result;
}
console.log(generateDateList('2014-2-27', '2014-3-2'));
I test it from chrome and nodejs below are the result.
[ '2014-02-27',
'2014-02-28',
'2014-02-29',
'2014-02-30',
'2014-02-31',
'2014-03-01',
'2014-03-02' ]
yeh big leap year:-D..., how can i fix this? or is there any better way.?
const listDate = [];
const startDate ='2017-02-01';
const endDate = '2017-02-10';
const dateMove = new Date(startDate);
let strDate = startDate;
while (strDate < endDate) {
strDate = dateMove.toISOString().slice(0, 10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate() + 1);
};
Take the start date and increment it by one day until you reach the end date.
Note: MySQL dates are standard format, no need to parse it by hand just pass it to the Date constructor: new Date('2008-06-13').
const addDays = (date, days = 1) => {
const result = new Date(date);
result.setDate(result.getDate() + days);
return result;
};
const dateRange = (start, end, range = []) => {
if (start > end) return range;
const next = addDays(start, 1);
return dateRange(next, end, [...range, start]);
};
const range = dateRange(new Date("2014-02-27"), new Date("2014-03-02"));
console.log(range);
console.log(range.map(date => date.toISOString().slice(0, 10)))
Here I use a recursive function, but you could achieve the same thing using a while (see other answers).
I have used this one from
https://flaviocopes.com/how-to-get-days-between-dates-javascript/
const getDatesBetweenDates = (startDate, endDate) => {
let dates = []
//to avoid modifying the original date
const theDate = new Date(startDate)
while (theDate < new Date(endDate)) {
dates = [...dates, new Date(theDate)]
theDate.setDate(theDate.getDate() + 1)
}
dates = [...dates, new Date(endDate)]
return dates
}
Invoke the function as follows:
getDatesBetweenDates("2021-12-28", "2021-03-01")
Note - I just had to fix issues with the Date object creation (new Date()) in the while loop and in the dates array. Other than that the code is pretty much same as seen on the above link
dateRange(startDate, endDate) {
var start = startDate.split('-');
var end = endDate.split('-');
var startYear = parseInt(start[0]);
var endYear = parseInt(end[0]);
var dates = [];
for(var i = startYear; i <= endYear; i++) {
var endMonth = i != endYear ? 11 : parseInt(end[1]) - 1;
var startMon = i === startYear ? parseInt(start[1])-1 : 0;
for(var j = startMon; j <= endMonth; j = j > 12 ? j % 12 || 11 : j+1) {
var month = j+1;
var displayMonth = month < 10 ? '0'+month : month;
dates.push([i, displayMonth, '01'].join('-'));
}
}
return dates;
}
var oDate1 = oEvent.getParameter("from"),
oDate2 = oEvent.getParameter("to");
var aDates = [];
var currentDate = oDate1;
while (currentDate <= oDate2) {
aDates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
I expanded Công Thắng's great answer to return {years, months, days}, thought it was worth sharing:
function getDates(startDate, endDate) {
const days = [],
months = new Set(),
years = new Set()
const dateMove = new Date(startDate)
let date = startDate
while (date < endDate){
date = dateMove.toISOString().slice(0,10)
months.add(date.slice(0, 7))
years.add(date.slice(0, 4))
days.push(date)
dateMove.setDate(dateMove.getDate()+1) // increment day
}
return {years: [...years], months: [...months], days} // return arrays
}
console.log(getDates('2016-02-28', '2016-03-01')) // leap year
/* =>
{
years: [ '2016' ],
months: [ '2016-02', '2016-03' ],
days: [ '2016-02-28', '2016-02-29', '2016-03-01' ]
}
*/
const {months} = getDates('2016-02-28', '2016-03-01') // get only months
Basically the function just increments the built-in Date object by one day from start to end, while the Sets capture unique months and years.

Categories

Resources