mde / timezone-js

DEPRECATED: Timezone-enabled JavaScript Date object. Uses Olson zoneinfo files for timezone data.
824 stars 183 forks source link

date.setMonth() on a date outputs wrong month #168

Closed yongzhihuang closed 4 years ago

yongzhihuang commented 9 years ago

Hi I'm running into a bit of problem here. It's better explain it by code below. There seems to be a error with properly setting the month for February.

var timezone = 'America/New_York';

var _tz = timezoneJS.timezone; _tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD; _tz.loadZoneJSONData('major_cities.json', true);

timezoneJS.timezone._useCache = false; var date = new timezoneJS.Date(timezone);

console.log('setting month to 1'); date.setMonth(1); console.log(date);

console.log('setting month to 1'); date.setMonth(1); console.log(date);

console.log('setting month to 2'); date.setMonth(2); console.log(date);

console.log('setting month to 3'); date.setMonth(3); console.log(date);

I'm getting the following output

setting month to 1 <----this is wrong! setting month to 1, but what's returned is 2 2 setting month to 1 1 setting month to 2 2 setting month to 3 3

As you can see, on the initial setMonth(), i'm getting a value of '2' returned. but any subsequent setMonth() are correct.

Do you know why this might be?

Thanks

vclayton commented 9 years ago

Looks like you filed this in January 30th. var date = new timezoneJS.Date(timezone); That gives you today's date, January 30th. The setMonth() function uses 0-based month numbers. If you try to set the month to 1, you are asking for January 30th to become February 30th. This date is not valid, so javascript will assume you wanted the 30th day from February 1, which is March 2. March is month 2.

Other months will have the same problem, it's just more visible with February. Ex:

var date = new timezoneJS.Date('2015-03-31', 'UTC');
date.setMonth(3);
date.toString(); // "2015-05-01 00:00:00"
yongzhihuang commented 9 years ago

Thanks for the reply. Is there a suggestion to work around this?

vclayton commented 9 years ago

You can pass setMonth() a day value as a second parameter (I'm assuming you are only interested in the month so day 1 is the simplest), but it will still apply the month parameter first.

It does work if you use setFullYear(year, month, day), like so:

var date = new timezoneJS.Date('2015-03-31', 'UTC');
date.setFullYear(date.getFullYear(), 3, 1);
date.toString(); // "2015-04-01 00:00:00"
alexkehayias commented 9 years ago

I also noticed this issue. The workaround described by @vclayton works. Does this only effect February?

mde commented 4 years ago

This library is no longer maintained, and this repo is here only for historical interest.