Home > Net >  Getting Date 30 days in Typescript
Getting Date 30 days in Typescript

Time:12-07

I am new to Typescript and trying to get the date (X) amount of months or days from now, in the newDate format specified below...

When I try to add one month:

var dateObj = new Date();
var month = dateObj.getUTCMonth()   2;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

var newDate = month   "/"   day   "/"   year;

It returns:

13/6/2022

When I try to add 30 days instead:

var dateObj = new Date();
var month = dateObj.getUTCMonth()   1;
var day = dateObj.getUTCDate()   30;
var year = dateObj.getUTCFullYear();

var newDate = month   "/"   day   "/"   year;

It returns this:

12/36/2022

So not only are the month & day incorrect in the example, the year doesn't advance either.

Any ideas?

CodePudding user response:

Without using Moment or any other library you can use setDate() and getDate() functions to manipulate value of dateObj:

// hard-coded date to illustrate automatic handling of year/month change
var dateObj = new Date('2022-12-06');

// add 30 days
dateObj.setDate(dateObj.getDate()   30); // 2023-01-05

var month = dateObj.getUTCMonth()   1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

var newDate = month   "/"   day   "/"   year;

console.log(newDate)

Notice how it automatically takes care of changing the month and year automatically for you.

CodePudding user response:

Simply set date with setSate() function.

var future = new Date();
future.setDate(future.getDate()   X_DAYS);

CodePudding user response:

As shown in this answer, you can rely on the Date object's ability to accept and handle invalid (out of range) values when adjusting specific components (e.g. day of month) — it will wrap the number and algorithmically determine how to handle the overflow (remainder), applying it to the next component (e.g. month).

e.g. In the details, adding 30 to 6 results in 36 as the new day of month — that's not a valid value for any month in the JS Date object.

If you don't want to rely on that kind of behavior for some reason — maybe you want a conceptual solution that you could apply to another language or date framework that doesn't handle overflow for you — then you can also adjust the numeric date representation manually using a bit of unit conversion math:

TS Playground

const date = new Date(Date.UTC(2022, 11, 6));
console.log(date.toISOString()); // 2022-12-06T00:00:00.000Z

const dayInMs = 1000 * 60 * 60 * 24;
//              ms/s      min/hr
//                    s/min     hr/day

date.setTime(date.getTime()   (30 * dayInMs));
//           ^^^^^^^^^^^^^^    ^^^^^^^^^^^^
//           date in ms        30 days in ms

console.log(date.toISOString()); // 2023-01-05T00:00:00.000Z

  • Related