Person
Person

Reputation: 2259

How to calculate a date depending on given granularity and another date in js?

I have two dates - date_to = new Date() and date_from which should be

date_from = date_to - 10 * granularity units

granularity can be hour, day, week and month

So far I have these constants

const MS_PER_DAY = 1000 * 60 * 60 * 24;
const MS_PER_HOUR = 1000 * 60 * 60;
const MS_PER_WEEK = 1000 * 60 * 60 * 24 * 7;

And I transforming date like so

const utc1 = Date.UTC(date_to.getFullYear(), date_to.getMonth(), date_to.getDate());

But I'm, now sure how to get my second date by given formula. All the help will be appreciated.

Upvotes: 1

Views: 338

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

You pretty much have it:

date_from = new Date(date_to.getTime() - 10 * granularity);

getTime returns milliseconds-since-the-Epoch, and your granularity values are in milliseconds, and when you pass a number into new Date, it uses it as miliseconds-since-The-Epoch. (You don't technically need the getTime call, since using a date in a subtraction expression will trigger its valueOf method, which for Dates is the same as getTime. But for clarity...)

Example:

const MS_PER_DAY = 1000 * 60 * 60 * 24;
const MS_PER_HOUR = 1000 * 60 * 60;
const MS_PER_WEEK = 1000 * 60 * 60 * 24 * 7;

const date_to = new Date(2018, 8, 1); // Sep 1 2018

const granularity = MS_PER_DAY;

const date_from = new Date(date_to.getTime() - 10 * granularity);

console.log("date_to:     " + date_to.toISOString());
console.log("granularity: MS_PER_DAY");
console.log("date_from:   " + date_from.toISOString());

Upvotes: 2

Related Questions