moment / moment-timezone

Timezone support for moment.js
momentjs.com/timezone
MIT License
3.83k stars 838 forks source link

subtract(2, 'month').startOf('month') giving utc time without offset even if timezone is provided #1061

Closed AvinashUtekar closed 1 year ago

AvinashUtekar commented 1 year ago

Environment

For bug reports, please run the following code in your environment and include the output:

{
  moment: '2.29.4',
  momentTz: '0.5.43',
  date: 'Wed May 10 2023 12:52:00 GMT+0530 (India Standard Time)',
  intlZone: 'Asia/Calcutta'
}

Issue description

const moment = require('moment-timezone');
// Define the target timezone
const targetTimezone = 'Europe/Lisbon';
// Get the current date in the target timezone
const currentDateLisbon = moment().tz(targetTimezone);
// Get the start and end of month in Lisbon time
const startOfMonthLisbon = currentDateLisbon.clone().subtract(2, 'month').startOf('month');
const endOfMonthLisbon = currentDateLisbon.clone().subtract(2, 'month').endOf('month');

console.log('Start of Month (Lisbon Time):', startOfMonthLisbon.format());
console.log('End of Month (Lisbon Time):', endOfMonthLisbon.format());

OUTPUT:

Start of Month (Lisbon Time): 2023-03-01T00:00:00Z
End of Month (Lisbon Time): 2023-03-31T23:59:59+01:00

if you see start of month gives time utc without offset and end of month gives time with offset so when we convert them to UTC , result is become incorrect. see below code

// converting above lisbon time to equivalent UTC time
const startOfMonthUtc = startOfMonthLisbon .clone().utc();
const endOfMonthUtc = endOfMonthLisbon.clone().utc();
console.log(startOfMonthUtc.format());
console.log(endOfMonthUtc.format());

OUTPUT

2023-03-01T00:00:00Z  // it should be 2023-02-28T23:00:00Z
2023-03-31T22:59:59Z

i have observed that , if we substract one month then strartOf('month') gives date with offset but if substract greater than one month then there is issue

gilmoreorless commented 1 year ago

This is correct. Portugal started Daylight Saving Time on March 26. Therefore: