2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-03-18 12:36:00 +00:00
|
|
|
// This module is browser compatible.
|
|
|
|
|
2024-03-26 10:54:12 +00:00
|
|
|
import { DateTimeFormatter } from "./_date_time_formatter.ts";
|
2022-12-19 10:24:48 +00:00
|
|
|
|
|
|
|
/**
|
2024-03-26 10:53:58 +00:00
|
|
|
* Parses a date string using the specified format string.
|
2022-12-19 10:24:48 +00:00
|
|
|
*
|
2024-01-12 04:37:19 +00:00
|
|
|
* The following symbols from
|
|
|
|
* {@link https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table | unicode LDML}
|
|
|
|
* are supported:
|
2024-03-26 10:53:58 +00:00
|
|
|
* - `yyyy` - numeric year
|
|
|
|
* - `yy` - 2-digit year
|
|
|
|
* - `M` - numeric month
|
|
|
|
* - `MM` - 2-digit month
|
|
|
|
* - `d` - numeric day
|
|
|
|
* - `dd` - 2-digit day
|
|
|
|
* - `H` - numeric hour (0-23 hours)
|
|
|
|
* - `HH` - 2-digit hour (00-23 hours)
|
|
|
|
* - `h` - numeric hour (1-12 hours)
|
|
|
|
* - `hh` - 2-digit hour (01-12 hours)
|
|
|
|
* - `m` - numeric minute
|
|
|
|
* - `mm` - 2-digit minute
|
|
|
|
* - `s` - numeric second
|
|
|
|
* - `ss` - 2-digit second
|
|
|
|
* - `S` - 1-digit fractional second
|
|
|
|
* - `SS` - 2-digit fractional second
|
|
|
|
* - `SSS` - 3-digit fractional second
|
|
|
|
* - `a` - dayPeriod, either `AM` or `PM`
|
|
|
|
* - `'foo'` - quoted literal
|
|
|
|
* - `./-` - unquoted literal
|
|
|
|
*
|
|
|
|
* @param dateString The date string to parse.
|
|
|
|
* @param formatString The date time string format.
|
|
|
|
* @return The parsed date.
|
2024-01-12 04:37:19 +00:00
|
|
|
*
|
2024-04-11 11:31:27 +00:00
|
|
|
* @example Basic usage
|
2022-12-19 10:24:48 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { parse } from "@std/datetime/parse";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2022-12-19 10:24:48 +00:00
|
|
|
*
|
2024-06-03 04:10:27 +00:00
|
|
|
* assertEquals(parse("01-03-2019 16:30", "MM-dd-yyyy HH:mm"), new Date(2019, 0, 3, 16, 30));
|
2024-03-26 10:53:58 +00:00
|
|
|
*
|
2024-06-03 04:10:27 +00:00
|
|
|
* assertEquals(parse("01-03-2019 16:33:23.123", "MM-dd-yyyy HH:mm:ss.SSS"), new Date(2019, 0, 3, 16, 33, 23, 123));
|
2024-03-26 10:53:58 +00:00
|
|
|
* ```
|
2022-12-19 10:24:48 +00:00
|
|
|
*/
|
|
|
|
export function parse(dateString: string, formatString: string): Date {
|
|
|
|
const formatter = new DateTimeFormatter(formatString);
|
2024-08-08 16:31:48 +00:00
|
|
|
return formatter.parse(dateString);
|
2022-12-19 10:24:48 +00:00
|
|
|
}
|