Finding date by subtracting X number of days from

2019-01-05 02:59发布

I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other is the number of days that needs to be subtracted.

For example, I pass my argument date as 27 July 2009 and i pass my other argument as 3. So i want to calculate the date 3 days before 27 July 2009. So the resultant date that we should get is 24 July 2009. How is this possible in JavaScript. Thanks for any help.

9条回答
▲ chillily
2楼-- · 2019-01-05 03:37

Never go for this solution yourDate.setDate(yourDate.getDate() - daysToSubtract);

it wont work in case your date is 1st of any month and you want to delete some days say 1.

Instead go for below solution which will work always

var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );

查看更多
叼着烟拽天下
3楼-- · 2019-01-05 03:51

This is what I would do. Note you can simplify the expression, I've just written it out to make it clear you are multiplying the number of days by the number of milliseconds in a day.

 var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
查看更多
闹够了就滚
4楼-- · 2019-01-05 03:51

Just another option, which I wrote:

DP_DateExtensions Library

It's probably overkill if ALL you want to do is one calculation, but if you're going to do more date manipulation you might find it useful.

Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-05 03:54

this is in reference to above answer check this fiddle

https://jsfiddle.net/uniyalguru/azh65aa0/

function Cureent_Date() {
var today_GMT = new Date();
var dd = today_GMT.getDate();
var mm = today_GMT.getMonth() + 1; //January is 0!
var yyyy = today_GMT.getFullYear();
if (dd < 10) {
    dd = '0' + dd
}
if (mm < 10) {
    mm = '0' + mm
}
current_date = mm + '/' + dd + '/' + yyyy;
查看更多
干净又极端
6楼-- · 2019-01-05 04:00

Simply:

yourDate.setDate(yourDate.getDate() - daysToSubtract);
查看更多
太酷不给撩
7楼-- · 2019-01-05 04:00

Here's an example, however this does no kind of checking (for example if you use it on 2009/7/1 it'll use a negative day or throw an error.

function subDate(o, days) {
// keep in mind, months in javascript are 0-11
return new Date(o.getFullYear(), o.getMonth(), o.getDate() - days);;
}
查看更多
登录 后发表回答