Created
September 26, 2019 10:47
-
-
Save theCrius/725f8ede459d59cc7f00e2366bf002aa to your computer and use it in GitHub Desktop.
Ngb-UK-Parser-Formatter.ts
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 { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap'; | |
@Injectable() | |
export class NgbDateUKParserFormatter extends NgbDateParserFormatter { | |
parse(value: string): NgbDateStruct { | |
if (value) { | |
const dateParts = value.trim().split('/'); | |
if (dateParts.length === 1 && isNumber(dateParts[0])) { | |
return {year: toInteger(dateParts[0]), month: null, day: null}; | |
} else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) { | |
return {year: toInteger(dateParts[1]), month: toInteger(dateParts[0]), day: null}; | |
} else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) { | |
return {year: toInteger(dateParts[2]), month: toInteger(dateParts[1]), day: toInteger(dateParts[0])}; | |
} | |
} | |
return null; | |
} | |
format(date: NgbDateStruct): string { | |
let stringDate = ''; | |
if (date) { | |
stringDate += isNumber(date.day) ? padNumber(date.day) + '/' : ''; | |
stringDate += isNumber(date.month) ? padNumber(date.month) + '/' : ''; | |
stringDate += date.year; | |
} | |
return stringDate; | |
} | |
} | |
function padNumber(value: number) { | |
if (isNumber(value)) { | |
return `0${value}`.slice(-2); | |
} else { | |
return ''; | |
} | |
} | |
function isNumber(value: any): boolean { | |
return !isNaN(toInteger(value)); | |
} | |
function toInteger(value: any): number { | |
return parseInt(`${value}`, 10); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment