Skip to content

Commit

Permalink
handle year date conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
snewcomer committed Jun 30, 2021
1 parent 8788826 commit bf23b5a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
9 changes: 7 additions & 2 deletions addon/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,18 @@ export default function validateDate(value, options) {
*/
export function parseDate(date, format, locale) {
if (format) {
let yearOnly = Object.keys(format).length === 1 && format.year;

if (!(date instanceof Date)) {
// format date into string
// we have already checked this a valid date
return new Intl.DateTimeFormat(locale, format).format(new Date(date));
let d = yearOnly ? new Date(date, 0) : new Date(date);
return new Intl.DateTimeFormat(locale, format).format(d);
}

// format date into string
return new Intl.DateTimeFormat(locale, format).format(date);
let d = yearOnly ? new Date(date.getFullYear(), 0) : new Date(date);
return new Intl.DateTimeFormat(locale, format).format(d);
} else {
// Date constructor accepts a variety of formats including properly represented strings and Date instances.
// However, a variety of formats return an "Invalid Date" literal including DD/MM/YYYY
Expand Down
17 changes: 12 additions & 5 deletions tests/unit/validators/date-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,21 +154,28 @@ test('before or on', function (assert) {
assert.equal(processResult(result), true);

options = {
onOrBefore: '2015',
onOrBefore: new Date(2015, 0),
format: { year: 'numeric' },
};
result = validate(new Date('2015'), cloneOptions(options));
result = validate(new Date(2015, 0), cloneOptions(options));
assert.equal(processResult(result), true);

result = validate(new Date('2016'), cloneOptions(options));
assert.equal(processResult(result), 'This field must be on or before 2013');
result = validate(new Date(2016, 0), cloneOptions(options));
assert.equal(processResult(result), 'This field must be on or before 2015');

options = {
onOrBefore: new Date('2015'),
format: { year: 'numeric' },
};
result = validate(new Date('2015'), cloneOptions(options));
assert.equal(processResult(result), true);
assert.equal(processResult(result), true, 'same dates with onOrBefore Date instance');

options = {
onOrBefore: '2015',
format: { year: 'numeric' },
};
result = validate(new Date('2015'), cloneOptions(options));
assert.equal(processResult(result), true, 'same dates with onOrBefore string')
});

test('before now or on', function (assert) {
Expand Down

0 comments on commit bf23b5a

Please sign in to comment.