JavaScript calculating date from today date to 7 days before

Pure js one line solution:

const sevenDaysAgo: Date = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)  
  1. new Date() - create Date object from calculated milliseconds time.
  2. Date.now() - gives time in milliseconds from 1970 to now.
  3. 7 (days) * 24 (hours) * 60 (minutes) * 60 (seconds) * 1000 (milliseconds ) = 604800000 (7 days in milliseconds).

You can use calculated value if you have no plans to change substracted value, or computed for easy change of substracted amount of days, minutes and so on.


Date manipulation library

If you plan to work more often with dates and time, I recommend to use Luxon if you care about timezones, date-fns which is smaller or dayjs which is even smaller but with less features. Compare

import { format, formatDistance, formatRelative, subDays } from 'date-fns'

format(new Date(), "'Today is a' eeee")
//=> "Today is a Friday"

formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"

formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."

Why not moment.js?

Moment.js is considered to be a legacy project in maintenance mode. It is not dead, but it is indeed done. See https://momentjs.com/docs/#/-project-status/


Problem is solved

var days; // Days you want to subtract
var date = new Date();
var last = new Date(date.getTime() - (days * 24 * 60 * 60 * 1000));
var day =last.getDate();
var month=last.getMonth()+1;
var year=last.getFullYear();