Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 30 days prior to current date?

People also ask

How to get 30 days back date using moment?

To get the date that is 30 days prior to the current date with JavaScript, we can call the setDate method with the current date subtracted by 30 to get the date 30 days before the current date. We can also use the subtract or add methods that come with moment. js to get the date that's 30 days before today.


Try this

var today = new Date()
var priorDate = new Date().setDate(today.getDate()-30)

As noted by @Neel, this method returns in Javascript Timestamp format. To convert it back to date object, you need to pass the above to a new Date object; new Date(priorDate).


Try using the excellent Datejs JavaScript date library (the original is no longer maintained so you may be interested in this actively maintained fork instead):

Date.today().add(-30).days(); // or...
Date.today().add({days:-30});

[Edit]

See also the excellent Moment.js JavaScript date library:

moment().subtract(30, 'days'); // or...
moment().add(-30, 'days');

Here's an ugly solution for you:

var date = new Date(new Date().setDate(new Date().getDate() - 30));

startDate = new Date(today.getTime() - 30*24*60*60*1000);

The .getTime() method returns a standard JS timestamp (milliseconds since Jan 1/1970) on which you can use regular math operations, which can be fed back to the Date object directly.


Get next 30th day from today

let now = new Date()
console.log('Today: ' + now.toUTCString())
let next30days = new Date(now.setDate(now.getDate() + 30))
console.log('Next 30th day: ' + next30days.toUTCString())

Get last 30th day form today

let now = new Date()
console.log('Today: ' + now.toUTCString())
let last30days = new Date(now.setDate(now.getDate() - 30))
console.log('Last 30th day: ' + last30days.toUTCString())

Javascript can handle it without any external libraries.

var today = new Date();
var dateLimit = new Date(new Date().setDate(today.getDate() - 30));

document.write(today + "<br/>" + dateLimit)