Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NgbDateAdapter for Moment.js values
import { NgbDateAdapter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';
import * as moment from 'moment';
// Might need to polyfill depending on needed browser support...
const isInt = Number.isInteger;
@Injectable()
export class NgbMomentjsAdapter extends NgbDateAdapter<moment.Moment> {
fromModel(date: moment.Moment): NgbDateStruct {
if (!date || !moment.isMoment(date)) {
return null;
}
return {
year: date.year(),
month: date.month() + 1,
day: date.date(),
};
}
toModel(date: NgbDateStruct): moment.Moment {
if (!date || !isInt(date.day) || !isInt(date.day) || !isInt(date.day)) {
return null;
}
return moment(`${date.year}-${date.month}-${date.day}`, 'YYYY-MM-DD');
}
}
declare namespace jasmine {
interface Matchers<T> {
toBeSameMoment(expected: any, expectationFailOutput?: any): boolean;
}
}
import { NgbMomentjsAdapter } from "./ngb-momentjs-adapter";
import * as moment from 'moment';
const customMatchers = {
toBeSameMoment: (util, customEqualityTestsers) => {
return {
compare: (actual: moment.Moment, expected: moment.Moment) => {
const pass = !!expected && moment.isMoment(expected)
? expected.isSame(actual)
: expected === actual;
return {
pass: pass,
message: pass ? '' : `Expected ${actual ? actual.toISOString() : actual} to be equal to ${expected ? expected.toISOString() : expected}.`,
};
}
}
}
};
describe('NgbMomentjsAdapter', () => {
const adapter = new NgbMomentjsAdapter();
beforeEach(() => {
jasmine.addMatchers(customMatchers);
});
it('should roundtrip correctly', () => {
const scenarios = [
null,
moment('2016-01-01', 'YYYY-MM-DD'),
moment('2016-02-28', 'YYYY-MM-DD'),
moment('2016-02-29', 'YYYY-MM-DD'),
moment('2016-11-11', 'YYYY-MM-DD'),
moment('2016-06-25', 'YYYY-MM-DD'),
moment('2016-12-31', 'YYYY-MM-DD'),
];
scenarios.forEach(input => {
const ngbDate = adapter.fromModel(input);
const result = adapter.toModel(ngbDate);
expect(result).toBeSameMoment(input);
});
});
});
@loxy

This comment has been minimized.

Copy link

@loxy loxy commented Oct 4, 2018

if (!date || !isInt(date.day) || !isInt(date.day) || !isInt(date.day)) {
  return null;
}

should be

if (!date || !isInt(date.year) || !isInt(date.month) || !isInt(date.day)) {
  return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment