tomsmithweb tomsmithweb - 1 year ago 83
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
for the format.

Both work, but somehow cannot be used together.

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download