Subtract days from a date in JavaScript

2018-12-31 09:00发布

Does anybody know of an easy way of taking a date (e.g. Today) and going back X days?

So, for example, if I want to calculate the date 5 days before today.

30条回答
君临天下
2楼-- · 2018-12-31 09:48
var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);

If you're performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:

http://simonwillison.net/2007/Dec/3/datejs/

查看更多
怪性笑人.
3楼-- · 2018-12-31 09:50

Use MomentJS.

function getXDaysBeforeDate(referenceDate, x) {
  return moment(referenceDate).subtract(x , 'day').format('MMMM Do YYYY, h:mm:ss a');
}

var yourDate = new Date(); // let's say today
var valueOfX = 7; // let's say 7 days before

console.log(getXDaysBeforeDate(yourDate, valueOfX));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

查看更多
梦寄多情
4楼-- · 2018-12-31 09:50

The top answers led to a bug in my code where on the first of the month it would set a future date in the current month. Here is what I did,

curDate = new Date(); // Took current date as an example
prvDate = new Date(0); // Date set to epoch 0
prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time
查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 09:50

A easy way to manage dates is use Moment.js

You can use add. Example

var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days'); //Add 5 days to start date
alert(new_date);

Docs http://momentjs.com/docs/#/manipulating/add/

查看更多
长期被迫恋爱
6楼-- · 2018-12-31 09:50

var d = new Date();

document.write('Today is: ' + d.toLocaleString());

d.setDate(d.getDate() - 31);

document.write('<br>5 days ago was: ' + d.toLocaleString());

查看更多
听够珍惜
7楼-- · 2018-12-31 09:50

var date = new Date();
var day = date.getDate();
var mnth = date.getMonth() + 1;

var fDate = day + '/' + mnth + '/' + date.getFullYear();
document.write('Today is: ' + fDate);
var subDate = date.setDate(date.getDate() - 1);
var todate = new Date(subDate);
var today = todate.getDate();
var tomnth = todate.getMonth() + 1;
var endDate = today + '/' + tomnth + '/' + todate.getFullYear();
document.write('<br>1 days ago was: ' + endDate );

查看更多
登录 后发表回答