Adding days to a date in a loop, javascript - javascript

I feel like there is something I'm missing about this, I'm trying to add 7 days to a current date, then 14, then 21. What I'm ending up with is a compounding of intervals rather than current date + 7, then current date + 14 etc.
var date = new Date();
for(var i = 0; i < 4; i++){
var tempDate = date;
var repeatson = tempDate.setDate(date.getDate() + (i*7));
var repeats = new Date(repeatson);
console.log(repeats);
}
Results in:
"2015-03-17T21:03:13.326Z"
"2015-03-24T21:03:13.326Z"
"2015-04-07T20:03:13.326Z"
"2015-04-28T20:03:13.326Z"
Rather than the desired, 24th, 31st & 8th

var tempDate = date; simply assigns a reference to date. You are not creating a copy. Similarly, setDate does not return a new date, it mutates the date itself.
One solution would be to create a copy:
var tempDate = new Date(date);
Your loop could be simplified to
var repeats = (new Date(date)).setDate(date.getDate() + (i*7))

Related

Turning an Integer Value into a Date Using that Integer and the Current Month

I have a function in my MongoDB/Node backend where I calculate a nextPaymentDate based on a combination of the current date and value(s) in a field (which is an array) titled paymentDateInts.
I have some logic that determines what is the correct integer of these two to assign to nextPaymentDateInt. This looks like this:
let currentDate = new Date();
let currentDateInt = currentDate.getDate();
let paymentDateInts = [1, 15];
let firstDateInt = paymentDateInts[0];
let secondDateInt = paymentDateInts[1];
let nextPaymentDateInt;
if (firstDateInt < currentDateInt) {
nextPaymentDateInt = firstDateInt;
} else {
nextPaymentDateInt = secondDateInt;
}
However, I want nextPaymentDate to be a date, not an integer. So how do I take the integer returned from the above function, and then turn that into a date.
UPDATE:
It just occurred to me that this is a little more complicated than I first assumed. Because I need to generate a date using that integer and either the current month, or the following month - whichever should apply.
In other words, if the second value is 15, and today is the 10th, then I should get a date with the current month and the integer 15. However, if today's date is beyond that 15th, then the date calculated should be for the next month and the integer 1.
You can use the new Date(year, monthIndex, day); constructor to construct your Date object
let nextPaymentDate = new Date(d.getFullYear(), d.getMonth(), nextPaymentDateInt);
Note:
There's no need to declare useless variables such as paymentDateInts, firstDateInt and secondDateInt, just compare the currentDateInt with 15 and construct your Date accordingly:
let currentDate = new Date();
let currentDateInt = currentDate.getDate();
let nextPaymentDate;
if (15 >= currentDateInt) {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDateInt);
} else {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
}
Demo:
let currentDate = new Date();
let currentDateInt = currentDate.getDate();
var nextPaymentDate;
if (15 >= currentDateInt) {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDateInt);
} else {
nextPaymentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
}
console.log(nextPaymentDate);
As chŝdk says, you can write this in a lot less code, and you only need one Date. Just check the date with paymentDateInts[1], then set values accordingly:
var paymentDateInts = [1, 15];
var d = new Date();
if (d.getDate() < paymentDateInts[1]) {
d.setDate(paymentDateInts[1]);
} else {
d.setMonth(d.getMonth() + 1, paymentDateInts[0]);
}
console.log(d.toString());
If you want toget a date at the same month then use getFullYear(), getMonth() when creating a new Date:
let nextPaymentDate = new Data(currentDate.getFullYear(), currentDate.getMonth(), nextPaymentDateInt)
Else, if you need next month, then use currentDate.getMonth() + 1
You can use the setDate method. For example
let firstDateInteger = new Date();
firstDateInteger.setDate(paymentDateInts[0]);

How to calculate the number of gaps between two dates in js

I have two date with time:
YY:MM:DD hh:mm
This is the time period
I need to calculate gap and divide it into 'n' equal parts.
In order to build a graph
Pls Help
Because date is actually saved as an integer and only shown as
YY:MM:DD hh:mm
You can actually just take the two date variables and devide them by the n
gap = (date1 - date2)/n
and then you can get the intervals by just adding the gap multiple times
for(var i = 1; i <= n; i++){
newDate[i] = new Date(date2 + gap*i);
}
something like this?
you can operate directly with dates in javascript
var date1 = new Date(2017, 01, 01, 10, 15, 00);
var date2 = new Date(2016, 12, 01, 10, 14, 45);
var dateDiff = new Date(date1-date2); //this will return timestamp
var years = dateDiff.getFullYear() - 1970; //init date always is 1970
var months = dateDiff.getMonth();
var days = dateDiff.getDate();
var minutes = dateDiff.getMinutes();
var seconds = dateDiff.getSeconds();
alert(years + " years.\r " +
months + " months\r" +
days + " days\r" +
minutes + " minutes\r" +
seconds + " seconds");
I would suggest that you try out the momentjs library. It provides powerful functionalities for you to conveniently work with date objects.
For example, given 2 string dates that are properly formatted, you can get the precise difference between the 2 times easily like so:
let time1 = moment("04/09/2013 15:00:00");
let time2 = moment("04/19/2013 18:20:30");
let diffMilliseconds = time1.diff(time2); // gives the time difference in milliseconds
let diffDays = time1.diff(time2, 'days'); // gives the time difference in days
You can use the date object to convert the given time format to timestamp and then find difference between timestamp.
For example:
var date1 = "2017-03-04 11:22:22"
var date2 = "2017-03-04 13:11:42"
var timestamp1 = Date.parse(date1, "YYYY-MM-DD HH:mm:ss")
var timestamp2 = Date.parse(date2, "YYYY-MM-DD HH:mm:ss")
var difference = timestamp2 - timestamp1;
console.log(difference) //in milliseconds
Now you can divide the difference in to n parts and add to timestamp1 to get following timestamp based on difference/n interval.

Get Millis using only Year and Month

I need to get a MILLIS value only with Year and Month.
Important: I don't wanna to use Days, Hours, Seconds, etc.
I'm using the following:
for (var i = 0; i <= 11; i++) {
var d = new Date(date);
d.setMonth(i);
var span = $("<span>").addClass("calElement").attr("millis", d.getTime());
}
You need to construct a new date using the given year and a month from the loop, time is automatically set to 00:00:00.000.
var y = new Date(date).getFullYear(),
msecs = new Date(y, i, 1).getTime();
A live demo at jsFiddle.
If you want to include the month[i], just loop from 1 to 12.

TypeError: *.getMonth is not a function

I'm trying to build a javascript function that will auto-fill 14 days of a calendar with dates leading up to the last date, which is picked by a datepicker. So far my code is:
function filldates() {
datepicked = document.getElementById("period-ending").value;
s = datepicked.split('/');
enddate = new Date(s[2], s[0], s[1]);
date1 = enddate.setDate(enddate.getDate()-14);
day1 = date1.getMonth() + 1;
month1 = date1.getDate();
var firstday = day1 + '/' + month1;
document.getElementById("date-1").value = firstday;
}
However the developer's console keeps telling me that date1.getMonth is not a function. I'm confused because all of the tutorials and examples I've been looking at are based around something like: "var today = new Date(); var month = today.getMonth() + 1;"
Is this an implementation problem?
The setDate() function mutates its context date. It does not return a new Date instance.
If you want to create a new date instance that's some number of days ahead of another one:
function daysAfter(d, days) {
var nd = new Date(d.getTime());
nd.setDate(d.getDate() + days);
return nd;
}
Then if you've got a date, you can create a date 14 days after it like this:
var someDate = ... whatever ... ;
var fourteenDaysAfter = daysAfter(someDate, 14);
You can then use the .getMonth() and .getDate() accessors to do whatever formatting you want. Keep in mind that months are numbered from zero in JavaScript.
edit for dates before a date just pass a negative number.

Javascript validation of date select boxes

I have created 3 select boxes containing days, months and year. What I really would like is to check after the user has selected a date, if the date is over a year from the current date a message is displayed or so.
Im a little stumped on what to do. Any gidance would be great.
Thanks
var ddlYear = document.getElementById('ddlYear');
var ddlMonth = document.getElementById('ddlMonth');
var ddlDay = document.getElementById('ddlDay');
var y = ddlYear[ddlYear.selectedIndex];
var m = ddlMonth[ddlMonth.selectedIndex];
var d = ddlDay[ddlDay.selectedIndex];
// past
var dt = new Date((y+1), (m-1), d);
var moreThanOnYearAgo = dt < new Date();
// future
var dt2 = new Date((y-1), (m-1), d);
var moreThanOnYearAhead = dt2 > new Date();
The y+1 is because if we're adding one year, and are still less than new Date() (today), then it's more than one year ago.
The m-1 is because months in the Date constructor are an enum, which means January is 0.
Don't reinvent the wheel one more time. Use a library that does validation.
There are 31556926000 milliseconds in a year. Just convert that date to a timestamp and subrtact the current date from it. If the result is greater than 31556926000 from it, is over a year away.
var userDate = new Date("11/29/2010");
var now = new Date();
var year_ms = 31556926000;
if ( userDate.getTime() - now.getTime() >= year_ms ) {
// A year away
} else {
// less than a year away
}

Categories

Resources