Skip to content

Commit

Permalink
Merge pull request #15 from subeshb1/feature/add_parse
Browse files Browse the repository at this point in the history
Feature/add parse
  • Loading branch information
subeshb1 authored May 10, 2020
2 parents 4d9b0ae + b2cbee7 commit 81fca15
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/nepali-date-converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import {
IYearMonthDate,
IAdBs,
format,
Language
Language,
parse
} from './nepali-date-helper'

const dateSymbol = Symbol('Date')
Expand Down Expand Up @@ -36,6 +37,9 @@ export default class NepaliDate {
this[convertToBSMethod](new Date(argument))
break
case 'string':
const { date, year, month } = parse(argument)
this[setDayYearMonth](year, month, date)
this[convertToADMethod]()
break
case 'object':
if (argument instanceof Date) {
Expand Down Expand Up @@ -139,13 +143,15 @@ export default class NepaliDate {
}
}

format(formatString: string, language: Language): string {
format(formatString: string, language: Language = NepaliDate.language): string {
return format(this.getBS(), formatString, language)
}

static parse() {
return new NepaliDate()
static parse(dateString: string): NepaliDate {
const { date, year, month } = parse(dateString)
return new NepaliDate(year, month, date)
}

static now() {
return new NepaliDate()
}
Expand Down
23 changes: 23 additions & 0 deletions src/nepali-date-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1647,3 +1647,26 @@ export function format(bsDate: IYearMonthDate, stringFormat: string, language: L
})
.replace(/\\/g, '')
}

export function parse(dateString: string): IYearMonthDate {
const OFFICIAL_FORMAT = /(\d{4})\s*([/-]|\s+)\s*(\d{1,2})\s*([/-]|\s+)\s*(\d{1,2})/
const GEORGIAN_FORMAT = /(\d{1,2})\s*([/-]|\s+)\s*(\d{1,2})\s*([/-]|\s+)\s*(\d{4})/
let match: RegExpMatchArray | null
match = dateString.match(OFFICIAL_FORMAT)
if (match !== null) {
return {
year: parseInt(match[1], 10),
month: parseInt(match[3], 10) - 1,
date: parseInt(match[5], 10)
}
}
match = dateString.match(GEORGIAN_FORMAT)
if (match !== null) {
return {
year: parseInt(match[5], 10),
month: parseInt(match[3], 10) - 1,
date: parseInt(match[1], 10)
}
}
throw new Error('Invalid date format')
}

0 comments on commit 81fca15

Please sign in to comment.