tomsmithweb tomsmithweb - 4 months ago 15
Javascript Question

Today's date -30 days in JavaScript

I need to get today's date -30 days but in the format of: "2016-06-08"

I have tried

setDate(date.getDate() - 30);
for -30 days.

I have tried
date.toISOString().split('T')[0]
for the format.

Both work, but somehow cannot be used together.

Answer

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"
Comments