How to convert date values to number of days - javascript

I am trying to add days to a date. I am taking input from the user where I have separate input boxes for the each field like no. of years, no of months and no of days like this.
as you can see in the 2nd input field row I am accepting no of years, days, months, etc.
and in First row I am getting a proper date like : 2020 10 05 00 00 00
and then passing them to date constructor to gate date.
ex. Date firstdate = new Date(2020, 10, 05, 00, 00,00);
and I am adding days to the above date using the following function
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
I am adding days to the previous date by calling a function like this.
var newdate = firstdate.addDays(totaldays);
Now the problem is while I am calculating days it is not including leap years and months with their specified date. because I am calculating days like this way:
totaldays = (years * 365) + (months * 30) + days;
What is the way so I can add days perfectly? for example, if the user entered date like
2020 12 10 00 00 00
and add the number of days and years like this
1 year 3 months 0 days 00 00 00
so it should ideally calculate 3 months that is January, February, march, as the user has entered the date of December so next three months date should be added.
SO How do I get the perfect number of days?
Sorry, this question can feel so long or improper. but I am working on this from a week.
Note: I cannot use any external link, API, Library as this is a school project.
Any help will be great. also sorry for my English. I'm not a native speaker.

Let the Date object do it for you, by using getFullyear/setFullYear, getMonth/setMonth, and getDate/setDate. They handle rollover and leap years:
const yearsToAdd = 1;
const monthsToAdd = 3;
const daysToAdd = 0;
const date = new Date(2020, 12 - 1, 10);
console.log(date.toString());
date.setFullYear(date.getFullYear() + yearsToAdd);
date.setMonth(date.getMonth() + monthsToAdd);
date.setDate(date.getDate() + daysToAdd);
console.log(date.toString());
Just as an example of handling leap years, here's that code adding two days to Feb 28th 2020 (which was a leap year, so there was a Feb 29th):
const yearsToAdd = 0;
const monthsToAdd = 0;
const daysToAdd = 2;
const date = new Date(2020, 2 - 1, 28);
console.log(date.toString());
date.setFullYear(date.getFullYear() + yearsToAdd);
date.setMonth(date.getMonth() + monthsToAdd);
date.setDate(date.getDate() + daysToAdd);
console.log(date.toString());
Notice how it goes to March 1st, not March 2nd, as it does in 2019:
const yearsToAdd = 0;
const monthsToAdd = 0;
const daysToAdd = 2;
const date = new Date(2019, 2 - 1, 28);
console.log(date.toString());
date.setFullYear(date.getFullYear() + yearsToAdd);
date.setMonth(date.getMonth() + monthsToAdd);
date.setDate(date.getDate() + daysToAdd);
console.log(date.toString());

This is a duplicate of other questions:
Add A Year To Today's Date
JavaScript function to add X months to a date
Add days to JavaScript Date
To summarise some of the issues:
Days are not always 24 hours long where daylight saving occurs, so you must determine whether "adding 1 day" means adding 1 calendar day or adding 24 hours
Months are 28 to 31 days long, so adding 1 month adds a different number of days depending on the month you're adding to
Years are 365 or 366 days long. In a leap year, adding 1 year to 29 Feb adds 366 days and ends on 2 Mar. The following day, adding 1 year to 1 Mar ends on 1 Mar
There are other quirks with leap years and month lengths not mentioned above, such as 31 Aug + 1 month gives 1 Oct, because adding a month in August adds 31 days.
So you can either add business rules to deal with the quirks, or just let them happen.
In reagard to adding years, months and days, that can be done in one call to setFullYear:
date.setFullYear(date.getFullYear() + yearsToAdd,
date.getMonth() + monthsToAdd,
date.getDate() + daysToAdd);
Adding them all at once can have a different result to adding them one at a time.
Given that you are getting values for the year, month, day, etc. then the values to add, you can simply add corresponding values (ensuring you convert strings to numbers before adding) and call the Date constructor once:
let date = new Date(startYear + yearsToAdd,
startMonth - 1 + monthsToAdd, // Assuming user enters calendar month
startDay + daysToAdd,
startHour + hoursToAdd,
startMinute + minutesToAdd,
startSecond + secondsToAdd);

Related

Javascript Date object not showing correct month

I'm trying to use the Javascript Date object to calculate a date in the future (3 months from today). I am however getting unexpected results, specifically, when adding 3 months, the output date is 2025 (for time travelers, it's 2018 this year)!
Doing a simple console.log returns some unexpected results as below:
var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 3);
console.log("3 months from now: "+d.toLocaleDateString());
Returns:
// Note todays real date is 9 October 2018
Locale Time:10/9/2018 // This is correct
app.min.js:1 Month: 9 // No, the month is 10 (October)
app.min.js:1 3 months from now: 11/9/2025 // What?
What am I doing wrong?
The argument monthIndex is 0-based. This means that January = 0 and December = 11.
so your code can be like this :
var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 4);
console.log("3 months from now: "+d.toLocaleDateString());
Output will be
> "Locale Time:10/9/2018"
> "Month: 9" (October = 9 as monthIndex starts from 0)
> "3 months from now: 2/9/2019"

Get same weekend last year using moment js

I'm trying to get the same day of the year last week so i can compare some analytics.
Using moment i can easily do this
var today = new Date();
//Sunday 4 September 2016 - Week 36
var lastYear = new moment(today).subtract(12, 'months').toDate();
//Friday 4 September 2015 - Week 37
What i am trying to do is get the same 'Sunday' last year, so Sunday week 36 2015
Any idea how to do this?
Here's what I came up with:
let today = moment();
let lastYear = moment().subtract(1, 'year')
.isoWeek(today.isoWeek())
.isoWeekday(today.isoWeekday());
It takes today as start point, subtracts a year, and sets the week and weekday to the ones from today.
So today (Tue Sept 13 2016, aka 2016-W37-2) last year was Tue Sept 8 2015 (aka 2015-W37-2).
// Typescript
var lastYear: moment.Moment = moment().subtract(1, "year");
As of version 2.0.0 moment.js supports .endOf('week') method, try
var lastYear = moment().subtract(1, 'years').endOf('week');
This will give you a 23:59:59 time, so you might also want to call .startOf('day') to get 00:00:00 of the same day:
var lastYear = moment().subtract(1, 'years').endOf('week').startOf('day');
Depending on your locale, your week may be from Monday to Sunday or from Sunday to Saturday, so I guess you'll have to account for that, too.
Edit
I've looked up documentation, and it appears you can set day of week this way, too:
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
So in your case it will be
var lastYear = moment().day(-52 * 7); // a Sunday 52 weeks ago
Or the two methods combined
var lastYear = moment().subtract(1, 'years').day(7); // a Sunday after the date that was 1 year ago

Are there any JavaScript methods that can replicate the Oracle's ADD_MONTH() functionality

1) Oracle's example of ADD_MONTHS(date, 1):
SELECT ADD_MONTHS('30-Nov-15', 3) FROM dual;
February, 29 2016 00:00:00
2) JavaScript:
var date= new Date("Mon Nov 30 2015 00:00:00");
date.setMonth(date.getMonth() + 3);
Tue Mar 01 2016 00:00:00
Are there any JavaScript methods that can replicate the Oracle's ADD_MONTH() functionality ?
If you want to implement the same logik as in Oracle function - i.e. for "shorter" month you do not overflow in the next month, I guess you will need to do it yourself:
Pseudocode:
myDay = date.getDate(); // save the date
date.setMonth(date.getMonth() + 3); // add months
myNewDay = date.getDate();
while (myDay != myNewDay & myNewDay <= 3) {
myNewDay = myNewDay -1 // go back one day
date.setDate(myNewDay); // restore the
}
So if you end with the same day of the month after adding months you are ready.
If you get a different day of month, it will be 1,2 or 3 (the difference in month length);
go back day by day until you reach the end of the month.
This is my knowledge of the Oracle algorithm. HTH.
date.getMonth()
returns the previous months date instead of this months date. So to add to the correct date just do
date.setMonth(date.getMonth() + 2);

Javascript adding days to a Date

Hi I am trying to create a variable today that is the current date today. I am trying to add 106 days to it which works successfully. Then I am trying to create a second variable today2 and subtract 31 days from the 'today' variable (current date + 106 -31). This part is not working. This is what it is giving me...
Thu Mar 28 11:52:21 EDT 2013
Tue Nov 27 11:52:21 EST 2012
The second line is not 31 days before the first line. Can someone help me correct this?
Feel free to play with my jsfiddle http://jsfiddle.net/fjhxW/
<div id="current"></div>
<div id="current2"></div>
<div id="current3"></div>
var today = new Date();
var today2 = new Date();
today.setDate(today.getDate() + 106);
today2.setDate(today.getDate() - 31);
var dd = today.getDate();
var mm = today.getMonth(); //January is 0!
var yy = today.getFullYear();
document.getElementById('current').innerHTML = today;
document.getElementById('current2').innerHTML = today2;
it's Xmas time so I give the answer just to copy/paste:
var oneDay = 24 * 60 * 60 * 1000, // 24h
today = new Date().getTime(), // in ms
firstDate,
secondDate;
firstDate = new Date(today + 106 * oneDay);
secondDate = new Date(firstDate.getTime() - 31 * oneDay);
try datejs:
Date.parse('t - 31 d'); // today - 31 days
Date.today().add(106).days().add(-31).days();
You cannot pass a negative number to setDate. setDate is used to set the date to set the absolute day, not relative days.
From the docs:
If the parameter you specify is outside of the expected range, setDate attempts to update the date information in the Date object accordingly. For example, if you use 0 for dayValue, the date will be set to the last day of the previous month.
A mathemathical solution:
Add 75 days to your current day (106 - 31), then add 31 days to that date. Change the order in what you are showing both dates on your code.
Why go forward and backward when you can always go forward?

Javascript - Previous month computation from a current date

I have a below JS where I get the max date that is user allowed to enter from a backend script:
var max_date = new Date(pdate + " " + ptime);
where pdate and ptime is fetched from a script.
Now I need to set the min date as 1 month less than max_date
if (max_date.getMonth() == 0)
subtractyear = 1;
var min_date = new Date(Date.UTC(max_date.getFullYear() - subtractyear,max_date.getMonth() - 1,max_date.getDate(),max_date.getHours(),0,0));
My issue is that if max_date is March 31 - then will the min_date be rolled over to Feb 28 or Feb 29 or Feb 31 or Feb 30?
If the date formed is an incorrect date - say Feb 30 how can I rectify this?
Simple subject the month by 1 would get a valid date -- never would setMonth method return an invalid Date object (the same as setDate, setYear and the Date constructor):
var date = new Date(2012, 02, 31); // 2012-03-31
date.setMonth(date.getMonth() - 1); // This gets 2012-03-02
I don't quite clear what date you expected, the last day of the previous month or just the day one month earlier?

Categories

Resources