diff --git a/src/util/datetime-util.ts b/src/util/datetime-util.ts index c8ad95c101..13efb5cc28 100644 --- a/src/util/datetime-util.ts +++ b/src/util/datetime-util.ts @@ -278,7 +278,7 @@ export function updateDate(existingData: DateTimeData, newData: any) { export function parseTemplate(template: string): string[] { - let formats: string[] = []; + const formats: string[] = []; template = template.replace(/[^\w\s]/gi, ' '); @@ -288,17 +288,19 @@ export function parseTemplate(template: string): string[] { } }); - let words = template.split(' ').filter(w => w.length > 0); + const words = template.split(' ').filter(w => w.length > 0); words.forEach((word, i) => { FORMAT_KEYS.forEach(format => { if (word === format.f) { if (word === FORMAT_A || word === FORMAT_a) { // this format is an am/pm format, so it's an "a" or "A" + console.log(`word: ${word}, words[i - 1]: ${words[i - 1]}`); + if ((formats.indexOf(FORMAT_h) < 0 && formats.indexOf(FORMAT_hh) < 0) || - (words[i - 1] !== FORMAT_m && words[i - 1] !== FORMAT_mm)) { + VALID_AMPM_PREFIX.indexOf(words[i - 1]) === -1) { // template does not already have a 12-hour format - // or this am/pm format doesn't have a minute format immediately before it - // so do not treat this word "a" or "A" as an am/pm format + // or this am/pm format doesn't have a hour, minute, or second format immediately before it + // so do not treat this word "a" or "A" as the am/pm format return; } } @@ -515,3 +517,7 @@ const MONTH_SHORT_NAMES = [ 'Nov', 'Dec', ]; + +const VALID_AMPM_PREFIX = [ + FORMAT_hh, FORMAT_h, FORMAT_mm, FORMAT_m, FORMAT_ss, FORMAT_s +]; diff --git a/src/util/test/datetime-util.spec.ts b/src/util/test/datetime-util.spec.ts index f42acf5080..850a145318 100644 --- a/src/util/test/datetime-util.spec.ts +++ b/src/util/test/datetime-util.spec.ts @@ -321,6 +321,13 @@ describe('parseTemplate', () => { expect(formats[2]).toEqual('a'); }); + it('should allow am/pm when using only 12-hour', () => { + var formats = datetime.parseTemplate('hh a'); + expect(formats.length).toEqual(2); + expect(formats[0]).toEqual('hh'); + expect(formats[1]).toEqual('a'); + }); + it('should allow am/pm when using 12-hour', () => { var formats = datetime.parseTemplate('hh:mm a'); expect(formats.length).toEqual(3); @@ -329,7 +336,7 @@ describe('parseTemplate', () => { expect(formats[2]).toEqual('a'); }); - it('should not add am/pm when not using 24-hour', () => { + it('should not add am/pm when using 24-hour', () => { var formats = datetime.parseTemplate('HH:mm a'); expect(formats.length).toEqual(2); expect(formats[0]).toEqual('HH');