Created
January 10, 2018 10:20
-
-
Save tomahim/a1d6fa0bdb30f27ad56b01ce019f2118 to your computer and use it in GitHub Desktop.
NgbDate momentJS adapter for Bootstrap datepicker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { NgbDateAdapter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap'; | |
import * as moment from 'moment'; | |
@Injectable() | |
export class NgbDateMomentAdapter extends NgbDateAdapter<moment.Moment> { | |
fromModel(date: moment.Moment): NgbDateStruct { | |
if (!date) { | |
return null; | |
} | |
return { year: date.year(), month: date.month(), day: date.day() }; | |
} | |
toModel(date: NgbDateStruct): moment.Moment { | |
if (!date) { | |
return null; | |
} | |
return moment(date.year + '-' + date.month + '-' + date.day, 'YYYY-MM-DD'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was a helpful reference implementation, but I believe there might be two bugs with it:
month()
in momentjs is zero-based so you need to offset for that in thefromModel(...)
method by adding+1
day()
in momentjs returns "day of week", so you'll wantdate()
insteadFor what it's worth to someone, I've created this public gist with a different implementation that doesn't seem to have those issues (and some jasmine tests to check that it doesn't).