(value: string | number | Date)
| 920 | * Throws if unable to convert to a date. |
| 921 | */ |
| 922 | export function toDate(value: string | number | Date): Date { |
| 923 | if (isDate(value)) { |
| 924 | return value; |
| 925 | } |
| 926 | |
| 927 | if (typeof value === 'number' && !isNaN(value)) { |
| 928 | return new Date(value); |
| 929 | } |
| 930 | |
| 931 | if (typeof value === 'string') { |
| 932 | value = value.trim(); |
| 933 | |
| 934 | if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) { |
| 935 | /* For ISO Strings without time the day, month and year must be extracted from the ISO String |
| 936 | before Date creation to avoid time offset and errors in the new Date. |
| 937 | If we only replace '-' with ',' in the ISO String ("2015,01,01"), and try to create a new |
| 938 | date, some browsers (e.g. IE 9) will throw an invalid Date error. |
| 939 | If we leave the '-' ("2015-01-01") and try to create a new Date("2015-01-01") the timeoffset |
| 940 | is applied. |
| 941 | Note: ISO months are 0 for January, 1 for February, ... */ |
| 942 | const [y, m = 1, d = 1] = value.split('-').map((val: string) => +val); |
| 943 | return createDate(y, m - 1, d); |
| 944 | } |
| 945 | |
| 946 | const parsedNb = parseFloat(value); |
| 947 | |
| 948 | // any string that only contains numbers, like "1234" but not like "1234hello" |
| 949 | if (!isNaN((value as any) - parsedNb)) { |
| 950 | return new Date(parsedNb); |
| 951 | } |
| 952 | |
| 953 | let match: RegExpMatchArray | null; |
| 954 | if ((match = value.match(ISO8601_DATE_REGEX))) { |
| 955 | return isoStringToDate(match); |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | const date = new Date(value as any); |
| 960 | if (!isDate(date)) { |
| 961 | throw new RuntimeError( |
| 962 | RuntimeErrorCode.INVALID_TO_DATE_CONVERSION, |
| 963 | ngDevMode && `Unable to convert "${value}" into a date`, |
| 964 | ); |
| 965 | } |
| 966 | return date; |
| 967 | } |
| 968 | |
| 969 | /** |
| 970 | * Converts a date in ISO8601 to a Date. |
no test coverage detected
searching dependent graphs…