MCPcopy Create free account
hub / github.com/angular/angular / toDate

Function toDate

packages/common/src/i18n/format_date.ts:924–969  ·  view source on GitHub ↗
(value: string | number | Date)

Source from the content-addressed store, hash-verified

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

Callers 2

formatDateFunction · 0.85

Calls 6

isDateFunction · 0.85
createDateFunction · 0.85
isoStringToDateFunction · 0.85
mapMethod · 0.80
testMethod · 0.45
matchMethod · 0.45

Tested by

no test coverage detected