Skip to content

Commit

Permalink
Merge pull request #4199 from Joddsson:fix-year-setter-for-leap-years
Browse files Browse the repository at this point in the history
[bugfix] Fix year setter on leap years, fixes #4024
  • Loading branch information
ichernev committed Oct 9, 2017
2 parents c037874 + 243e4e9 commit 36f29b3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/lib/moment/get-set.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { normalizeUnits, normalizeObjectUnits } from '../units/aliases';
import { getPrioritizedUnits } from '../units/priorities';
import { hooks } from '../utils/hooks';
import isFunction from '../utils/is-function';
import { daysInMonth } from '../units/month';
import { isLeapYear } from '../units/year';

export function makeGetSet (unit, keepTime) {
return function (value) {
Expand All @@ -22,7 +24,12 @@ export function get (mom, unit) {

export function set (mom, unit, value) {
if (mom.isValid() && !isNaN(value)) {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
if (unit === 'FullYear' && isLeapYear(mom.year())) {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
}
else {
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
}
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/test/moment/getters_setters.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,16 @@ test('day setter', function (assert) {
assert.equal(moment(a).day(17).date(), 26, 'set from wednesday to second next wednesday');
});

test('year setter', function (assert) {
var a = moment([2015, 3, 15]);
assert.equal(moment(a).year(2016).format('YYYY-MM-DD'), '2016-04-15', 'set from 2015 to 2016');
assert.equal(moment(a).year(2011).format('YYYY-MM-DD'), '2011-04-15', 'set from 2015 to 2011');

var b = moment([2012, 1, 29]);
assert.equal(moment(b).year(2017).format('YYYY-MM-DD'), '2017-02-28', 'set from last day of february on a leap year to a non leap year');
assert.equal(moment(b).year(2004).format('YYYY-MM-DD'), '2004-02-29', 'set from last day of february on a leap year to a leap year');
});

test('object set ordering', function (assert) {
var a = moment([2016,3,30]);
assert.equal(a.set({date:31, month:4}).date(), 31, 'setter order automatically arranged by size');
Expand Down

0 comments on commit 36f29b3

Please sign in to comment.