有没有一种简单的方法来获取olain JavaScript日期(例如今天)并返回X天?

例如,如果我想计算今天前5天的日期。


当前回答

我发现getDate()/setDate()方法的一个问题是,它太容易将所有内容转换为毫秒,而且语法有时我很难理解。

相反,我喜欢处理1天=86400000毫秒的事实。

因此,对于您的特定问题:

today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))

就像一个魅力。

我一直使用这种方法进行30/60/365天的滚动计算。

您可以很容易地推断出这一点,以创建月、年等的时间单位。

其他回答

var date=新日期();var day=date.getDate();var mnth=date.getMonth()+1;var fDate=day+'/'+mnth+'/'+date.getFullYear();document.write('今天是:'+fDate);var subDate=date.setDate(date.getDate()-1);var todate=新日期(subDate);var today=todate.getDate();var tomnth=todate.getMonth()+1;var endDate=today+'/'+tomnthe+'/'+todate.getFullYear();document.write('<br>1天前是:'+endDate);

您可以使用Javascript。

var CurrDate = new Date(); // Current Date
var numberOfDays = 5;
var days = CurrDate.setDate(CurrDate.getDate() + numberOfDays);
alert(days); // It will print 5 days before today

对于PHP,

$date =  date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
echo $date;

希望它对你有所帮助。

一些人建议在js中处理日期时,使用moment.js让您的生活更轻松。这些答案已经过去了,值得注意的是,moment.js的作者现在不鼓励使用它。主要是因为它的大小和缺乏树木摇晃支撑。

如果你想走图书馆路线,可以选择像卢克逊这样的其他路线。它比moment.js小得多(因为它巧妙地使用了Intl对象并支持树抖动),而且功能也和moment.js一样多。

要从今天起5天回到卢克逊,您需要:

import { DateTime } from 'luxon'

DateTime.now().minus({ days: 5 });

在不使用第二个变量的情况下,您可以用背部x天替换7:

let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))

如果你想把这一切都放在一行。

从今天起5天

//past
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));

特定日期后5天

 var pastDate = new Date('2019-12-12T00:00:00');

 //past
 var fiveDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
 //future
 var fiveDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));

我写了一个你可以使用的函数。

函数AddOrSubactDays(startingDate,number,add){if(添加){返回新日期(newDate().setDate(startingDate.getDate()+number));}其他{返回新日期(newDate().setDate(startingDate.getDate()-number));}}console.log('Today:'+new Date());console.log('Future:'+AddOrSubactDays(new Date(),5,true));console.log('Last:'+AddOrSubactDays(new Date(),5,false));