manuelmhtr / countries-and-timezones

Minimalistic library to work with countries and timezones data
MIT License
224 stars 67 forks source link

`getOffsetStr()` evaluates incorrectly for negative values #60

Closed dondevi closed 9 months ago

dondevi commented 9 months ago

The problem

The utcOffset of Pacific/Marquesas is -570, but utcOffsetStr returns -10:30.

What is expected

The utcOffsetStr returns -09:30.

What is happening

The code in src/build-timezone.js

function getOffsetStr(offset) {
  const hours = Math.floor(offset / 60);  // There may be a calculation error here
  const min = offset % 60;
  const sign = offset < 0 ? '-' : '+';

  return `${sign}${getNumStr(hours)}:${getNumStr(min)}`;
}

This evaluates incorrectly for negative values

Math.floor(570 / 60); // 9
Math.floor(-570 / 60); // -10

Suggest to fix

const hours = Math.floor(Math.abs(offset) / 60);
// or
const hours = ~~(offset / 60);
manuelmhtr commented 9 months ago

Hi @dondevi thanks a lot for reporting this issue and proposing a solution. It has been fixed in v3.5.2