Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

javascript - How to convert date values to number of days

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. image of interface

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...