Today's date -30 days in JavaScript

setDate() doesn't return a Date object, it returns the number of milliseconds since 1 January 1970 00:00:00 UTC. You need separate calls:

var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2016-06-08"

Please note that you would be better to use something like moment.js for this rather than reinventing the wheel. However a straight JS solution without libraries is something like:

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

sets date to 30 days ago. (JS automatically accounts for leap years and rolling over months less than 30 days, and into the previous year)

now just output it like you want (gives you more control over the output). Note we are prepending a '0' so that numbers less than 10 are 0 prefixed

var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2)

You're saying that those two lines worked for you and your problem is combining them. Here is how you do that:

var date = new Date();
date.setDate(date.getDate() - 30);
document.getElementById("result").innerHTML = date.toISOString().split('T')[0];
<div id="result"></div>

If you really want to subtract exactly 30 days, then this code is fine, but if you want to subtract a month, then obviously this code doesn't work and it's better to use a library like moment.js as other have suggested than trying to implement it by yourself.

Tags:

Javascript