Skip to content

Commit 0f79334

Browse files
committed
fix: correct handle fraction of a seconds in parseIso
closes #16
1 parent b13576a commit 0f79334

2 files changed

Lines changed: 21 additions & 3 deletions

File tree

src/parse/parse-iso.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ describe('parseIso', function() {
5656
dateStr: '2017-06-01T12:34:5',
5757
correctResult: null,
5858
},
59+
{
60+
/* NOTE too much seconds */
61+
dateStr: '2017-06-01T12:34:567',
62+
correctResult: null,
63+
},
5964
{
6065
dateStr: '',
6166
correctResult: null,
@@ -80,6 +85,16 @@ describe('parseIso', function() {
8085
dateStr: '2017-06-01T09:00+13:60',
8186
correctResult: null,
8287
},
88+
{
89+
/* NOTE there is no fractional milliseconds in Date object */
90+
dateStr: '2017-06-01T12:34:56.78999999999999999',
91+
correctResult: newValidDate(2017, Month.Jun, 1, 12, 34, 56, 789),
92+
},
93+
{
94+
/* NOTE there is no fractional milliseconds in Date object */
95+
dateStr: '2017-06-01T12:34:56.7890123456789-03:00',
96+
correctResult: newValidDate('2017-06-01T15:34:56.789Z'),
97+
},
8398
];
8499

85100
for (let i = 0; i < FORMATS.length; i++) {

src/parse/parse-iso.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@ import {ValidDate} from '../valid-date';
33
function toNumber(value: string | undefined, defaultValue: number) {
44
return typeof value === 'undefined' ? defaultValue : +value;
55
}
6+
function toNumberMs(value: string | undefined) {
7+
return typeof value === 'undefined' ? 0 : +value.substring(0, 4) * 1000;
8+
}
69

7-
// ( YYYY ) ( MM ) ( DD ) ( HH ) ( MM ) ( SS )( MS ) ( TZD )
8-
const ISO_RX = /^\s*(\d{4,6}?)(?:-?(\d\d))?(?:-?(\d\d))?(?:T(\d\d):?(\d\d):?(?:(\d\d)(\.\d{1,3})?)?([+-]\d\d?(?::\d\d)?|Z)?)?\s*$/;
10+
// ( YYYY ) ( MM ) ( DD ) ( HH ) ( MM ) ( SS )( MS ) ( TZD )
11+
const ISO_RX = /^\s*(\d{4,6}?)(?:-?(\d\d))?(?:-?(\d\d))?(?:T(\d\d):?(\d\d):?(?:(\d\d)(\.\d+)?)?([+-]\d\d?(?::\d\d)?|Z)?)?\s*$/;
912
export function parseIso(dateStr: string): ValidDate | null {
1013
if (!dateStr) return null;
1114
const timeList = dateStr.match(ISO_RX);
@@ -22,7 +25,7 @@ export function parseIso(dateStr: string): ValidDate | null {
2225
const H = toNumber(timeList[4], 0);
2326
const m = toNumber(timeList[5], 0);
2427
const s = toNumber(timeList[6], 0);
25-
const ms = toNumber(timeList[7], 0) * 1000;
28+
const ms = toNumberMs(timeList[7]);
2629

2730
const isTimeOk = H < 24 && m < 60 && s < 60;
2831
if (!isTimeOk) return null;

0 commit comments

Comments
 (0)