web123456

How to get n days ago date in JavaScript

// Get the date n days ago function before_date(n) { const time = (new Date).getTime() - 24 * 60 * 60 * 1000 * n; const date = new Date(time); // Get the current month let nowMonth = date.getMonth() + 1; // Get what number is currently let strDate = date.getDate(); // Add a separator- const seperator = "-"; // Process the month, add a 0 in front of January-September if (nowMonth >= 1 && nowMonth <= 9) { nowMonth = "0" + nowMonth; } // Process the date, add a 0 in front of the 1-9th period if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } // Finally splice the string and get a date in the format (yyyy-MM-dd) return date.getFullYear() + seperator + nowMonth + seperator + strDate; }