How to remove timezone from my two date values?

45 Views Asked by At

I use date-fns and I want to know the first day of the month and the last day.

The problem is get both but with 2 hours back so I get the previous month and the current month day minus one. How can I remove the timezone ?

expected output:

2024-04-01T00:00:00.000Z
2024-04-30T00:00:00.000Z

recieved output:

2024-03-31T22:00:00.000Z
2024-04-29T22:00:00.000Z

here is my code:

const { addMonths, lastDayOfMonth } = require('date-fns');

const today = new Date();

const monthPlusOne = addMonths(today, 1);

const firstDay = new Date(
  monthPlusOne.getFullYear(),
  monthPlusOne.getMonth(),
  1
);

const lastDay = lastDayOfMonth(firstDay);

console.log(firstDay);

console.log(lastDay);

1

There are 1 best solutions below

0
David Aniebo On BEST ANSWER

The dates are in UTC format, and the local time zone offset is causing the difference you're observing.

Here's an updated version of your code:

const { addMonths, lastDayOfMonth } = require('date-fns');

const today = new Date();

const monthPlusOne = addMonths(today, 1);

const firstDay = new Date(
monthPlusOne.getFullYear(),
monthPlusOne.getMonth(),
1
);

const lastDay = lastDayOfMonth(firstDay);

// Convert to ISO string and remove the 'Z' (UTC indicator)
const firstDayString = firstDay.toISOString().slice(0, -1);
const lastDayString = lastDay.toISOString().slice(0, -1);

console.log(firstDayString);
console.log(lastDayString);

Note: The dates are still in UTC, but the 'Z' indicating UTC has been removed from the string representation.