Increment JavasScript date object for next month when days are increased? - javascript

Is there a simple solution to auto increment the month of the date object when days are added via getDate?
I need to add 2 days to a user supplied date, for example if the user's entered value is 2014-11-16 it returns 2014-11-18.
I have this working in the below example, but the problem is if a user supplies a date at the end of the month, for example 2014-11-30 it will return 2014-11-32 (November only has 30 days) instead of rolling into the next month, it should be 2014-12-02.
It also does not increment to a new year as well.
var actualDate = new Date(arrive);
var year = actualDate.getFullYear();
var monthy = actualDate.getMonth()+1;
var days = actualDate.getDate()+2;
var out = year + '-' + (monthy < 10 ? '0' : '') + monthy + '-' + days;
http://jsfiddle.net/bubykx1t/

Just use the setDate() method.
var actualDate = new Date(arrive);
actualDate.setDate(actualDate.getDate() + 2);
Check out this link

You can create new Date objects based on the number of milliseconds since January 1, 1970, 00:00:00 UTC. Since the number of milliseconds in a minute, hour, day, week are set we can add a fixed amount to the current time in order to get a time in the future. We can forget about what day of the month, or year it is as it's inherent in the number of milliseconds that have passed since 1970.
This will keep adjust to days months and years correctly.
var numberOfDaysToIncrement = 7;
var offset = numberOfDaysToIncrement * 24 * 60 * 60 * 1000;
var date = new Date();
var dateIncremented = new Date(date.getTime() + offset);

Related

How to get date after n number of days in a date range?

Suppose I have a start date which is 3/Sep/2019 and end date 10/Sep/2019.
I want to get the date after 4 days from the starting date. So if my starting date is 3/sep/2019 I want to get 7/Sep/2019 but not 12/sep/2019 since this date comes after my end date.
How can I achieve this?
So far I'm getting dates after n number of dates like this:
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
date = new Date(res);
alert(date);
var days = 7;
var date = new Date();
var res = date.setDate(date.getDate() + days);
This is how you get a day 7 days after the date you already have. It wraps to the next month when appropriate as well.
Try the function I wrote below:
function getFutureDate(daysAhead) {
const date = new Date();
date.setDate(date.getDate() + daysAhead);
return date
}
const fourDays = getFutureDate(4)
console.log(fourDays)

Today's date -30 days in JavaScript

I need to get today's date -30 days but in the format of: "2016-06-08"
I have tried setDate(date.getDate() - 30); for -30 days.
I have tried date.toISOString().split('T')[0] for the format.
Both work, but somehow cannot be used together.
setDate() doesn't return a Date object, it returns the number of milliseconds since 1 January 1970 00:00:00 UTC. You need separate calls:
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2016-06-08"
You're saying that those two lines worked for you and your problem is combining them. Here is how you do that:
var date = new Date();
date.setDate(date.getDate() - 30);
document.getElementById("result").innerHTML = date.toISOString().split('T')[0];
<div id="result"></div>
If you really want to subtract exactly 30 days, then this code is fine, but if you want to subtract a month, then obviously this code doesn't work and it's better to use a library like moment.js as other have suggested than trying to implement it by yourself.
Please note that you would be better to use something like moment.js for this rather than reinventing the wheel. However a straight JS solution without libraries is something like:
var date = new Date();
date.setDate(date.getDate() - 30);
sets date to 30 days ago. (JS automatically accounts for leap years and rolling over months less than 30 days, and into the previous year)
now just output it like you want (gives you more control over the output). Note we are prepending a '0' so that numbers less than 10 are 0 prefixed
var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2)
// Format date object into a YYYY-MM-DD string
const formatDate = (date) => (date.toISOString().split('T')[0]);
const currentDate = new Date();
// Values in milliseconds
const currentDateInMs = currentDate.valueOf();
const ThirtyDaysInMs = 1000 * 60 * 60 * 24 * 30;
const calculatedDate = new Date(currentDateInMs - ThirtyDaysInMs);
console.log(formatDate(currentDate));
console.log(formatDate(calculatedDate));
Today's date -30 days in this format: "YYYY-MM-DD":
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2021-02-05"
Today's date -30 days but get all days in this format: "YYYY-MM-DD":
var daysDate = [];
for(var i = 1; i<= 30; i++) {
var date = new Date();
date.setDate(date.getDate() - i);
daysDate.push(date.toISOString().split('T')[0]); // ["2021-02-05", "2021-02-04", ...]
}
Simply you can calculate in terms of timestamp
var date = new Date(); // Current date
console.log(date.toDateString())
var pre_date = new Date(date.getTime() - 30*24*60*60*1000);
// You will get the Date object 30 days earlier to current date.
console.log(pre_date.toDateString())
Here 30*24*60*60*1000 refers to time difference in miliseconds.

Javascript Adding Time for a Future Date

I looked at some other questions, and don't see my specific problem, so please excuse me if it has been asked or answered.
What I am trying to do is figure out a simple "payment" calculator, and provide some additional information, such as the first payment date, and the last.
In some cases, the day of the last payment works, and sometimes it doesn't.
Here's my code:
var myDate = new Date();
var odo = document.contract.firstPaymentDate.value;
var n = odo.split("/");
var month = n[0];
var day = n[1];
var year = n[2];
var oldDateObj = new Date(year, month, day);
var newDateObj = new Date(oldDateObj.getTime() + ((document.contract.totalNumberRegularPayments.value - 1)*1209600*1000));
var dd = newDateObj.getDate();
var mm = newDateObj.getMonth();
var y = newDateObj.getFullYear();
var someFormattedDate = mm + '/'+ dd + '/'+ y;
document.contract.lastPaymentDate.value = someFormattedDate;
So I take the first payment date, and add 1209600 seconds times the number of payments (minus 1 since they have "already" paid the first).
This is based on starting at a specific day that can be chosen by the user.
So my example is 156 BiWeekly payments (so 155 for the calculations), which works out to 6 years. If I choose the date of the 1st, I get 10/01/2013 as the start, but 9/11/2019 as the end (First on a Tuesday, last on a Wednesday).
For the 15th (9/15/2013 - a Sunday - to 8/24/2019 - a Saturday)
For the 20th (9/20/2013 - a Friday - to 8/29/2013 - a Thursday)
So since sometimes it's a day later, and sometimes a day ahead, I can't just +1 to var dd = newDateObj.getDate();
I'm really baffled as to what's going on, and I'm hoping someone out there either has some experience with this, or someone that knows what the heck I might be doing wrong.
Thanks in advance for any help you can offer.
If you want to add a number of weeks, just add 7 times as many days, e.g.
var now = new Date();
// Add two weeks
now.setDate(now.getDate() + 14);
So if you have 24 fortnightly payments:
var now = new Date();
// Add 24 fortnights (48 weeks)
now.setDate(now.getDate() + 24 * 14);
or
now.setDate(now.getDate() + 24 * 2 * 7);
whatever you think is clearest.
If you want to have a start and end date:
var start = new Date();
var end = new Date(+start);
end.setDate(end.getDate() + 24 * 14);
alert('Start on: ' + start + '.\nEnd in 24 fortnights: ' + end);
Edit
Here's a working example:
<script>
function calcLastPayment(start, numPayments) {
if (typeof start == 'string') {
start = stringToDate(start);
}
var end = new Date(+start);
end.setDate(end.getDate() + --numPayments * 14)
return end;
}
// Expect date in US format m/d/y
function stringToDate(s) {
s = s.split(/\D/)
return new Date(s[2], --s[0], s[1])
}
</script>
<form>
<table>
<tr><td>Enter first payment date (m/d/y):
<td><input name="start">
<tr><td>Enter number of payments:
<td><input name="numPayments">
<tr><td colspan="2"><input type="button" value="Calc end date" onclick="
this.form.end.value = calcLastPayment(this.form.start.value, this.form.numPayments.value)
">
<tr><td>Last payment date:
<td><input readonly name="end">
<tr><td colspan="2"><input type="reset">
</table>
</form>
Given a first payment date of Thursday, 5 September and 3 repayments it returns Thursday 3 October, which seems correct to me (5 and 19 September and 3 October). It should work for any number of payments.
There is a simple way to do this in a line or two of code.
I use 864e5 for the number of milliseconds in a day. Because 1000 milliseconds/second * 60 seconds/minute * 60 minutes/hour * 24 hours/day = 86400000 milliseconds/day or 864e5.
var now = new Date,
day = 864e5,
weekFromNow = new Date(+now + day * 7); //+now casts the date to an integer
+now casts the date to an integer, the number of milliseconds. now.valueOf() works too.
day * 7 or 864e5 * 7 is the number of milliseconds in a week.
new Date(...) casts the number of milliseconds to a date again.
Sometimes you don't have to worry about casting the value back to a date.

Calculate the Date based on Current Date and No of Days using Javascript/Jquery

I need a help..
I have a Current Date and No of days column.
When i enter number of days,i should add current date plus no of days entered.
For example,
todays date 5th jan + 20(no of days) = 25th Jan 2011 in another column.
Kindly help me.
Thanks in Advance.
Date.js is fantastic for this.
Date.today().add(5).days();
As you are learning JavaScript you may find the w3schools site useful for simple examples of objects and functions that are exposed and how they may be used.
http://www.w3schools.com/jsref/jsref_obj_date.asp
You can calculate the date as follows:
var d = new Date(); // Gets current date
var day = 86400000; // # milliseconds in a day
var numberOfDays = 20;
d.setTime(d.getTime() + (day*numberOfDays)); // Add the number of days in milliseconds
You can then use one of the various methods of displaying the date:
alert(d.toUTCString());
You could do something like
Date.today().add(X).days();
Where X is the number of days the user has entered.
You can add dates like this in js:
var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
var month = someDate.getMonth() + 1; //Add 1 because January is set to 0 and Dec is 11
var day = someDate.getDate();
var year = someDate.getFullYear();
document.write(month + "/" + day + "/" + year);
See this p.cambell's answer here: How to add number of days to today's date?

Using answers from prompt for a calculation

Total newbie at JavaScript.
I would like to calculate how many days one has been alive by asking the user their date of birth via prompts/alerts, then obviously subtracting their date of birth from today's date.
I've made a bit of a start...
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
Any advice or help would be much appreciated.
You need to use the Date object (MDN). They can be created from a month, a day, and a year, and added/subtracted.
Typically :
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
Be aware of the fact that months starts at 0, e.g. January is 0.
var curDate = new Date();
gives you the current date.
var birthdate = new Date(year, month-1, day);
gives you a Date from the separate variables. NB the month is zero-based.
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));
Simply subtract current time from Jan 1 1970 in milliseconds from their birthdate's time from Jan 1 1970 in milliseconds. Then convert it to days. Look at MDN's Docs for more info.
See JSFiddle for a working example. Try entering yesterday's date. It should show 1 day.
Read some of this: http://www.w3schools.com/js/js_obj_date.asp

Categories

Resources