Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Today's date -30 days in JavaScript

Tags:

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.

like image 734
tomsmithweb Avatar asked Jul 08 '16 23:07

tomsmithweb


People also ask

How can I get days in current month?

To get the number of days in the current month: function getDaysInCurrentMonth() { const date = new Date(); return new Date( date. getFullYear(), date. getMonth() + 1, 0 ). getDate(); } const result = getDaysInCurrentMonth(); console.

How do you code a date in JavaScript?

We can create a date using the Date object by calling the new Date() constructor as shown in the below syntax. Syntax: new Date(); new Date(value); new Date(dateString); new Date(year, month, day, hours, minutes, seconds, milliseconds);


1 Answers

// Format date object into a YYYY-MM-DD string
const formatDate = (date) => (date.toISOString().split('T')[0]);

const currentDate = new Date();

// Values in milliseconds
const currentDateInMs = currentDate.valueOf();
const ThirtyDaysInMs = 1000 * 60 * 60 * 24 * 30;

const calculatedDate = new Date(currentDateInMs - ThirtyDaysInMs);

console.log(formatDate(currentDate));
console.log(formatDate(calculatedDate));
like image 55
Hyunbin Avatar answered Oct 20 '22 15:10

Hyunbin