Skip to content

Instantly share code, notes, and snippets.

@jeroenheijmans
Last active March 3, 2022 13:34
Show Gist options
  • Save jeroenheijmans/af473dad8ace3c5c4734588fca7d8b84 to your computer and use it in GitHub Desktop.
Save jeroenheijmans/af473dad8ace3c5c4734588fca7d8b84 to your computer and use it in GitHub Desktop.
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
Copy link

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