├── etc └── coverage │ └── .gitkeep ├── mod.ts ├── import_map.json ├── .vscode ├── extensions.json └── settings.json ├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── src ├── mod.ts ├── types.ts ├── polyfill.ts ├── cli.ts ├── to-temporal.ts ├── to-date.ts ├── locales │ ├── types.ts │ ├── tr-TR.ts │ ├── fr-FR.ts │ ├── it-IT.ts │ ├── de-DE.ts │ ├── en-GB.ts │ ├── en-US.ts │ ├── es-ES.ts │ ├── combiners.ts │ ├── generic-american.ts │ └── generic-europe-asia.ts ├── locales.ts ├── date-tokenizer.test.ts ├── date-tokenizer.ts ├── parser.ts ├── sample-dates.ts └── format-tokenizer.ts ├── .editorconfig ├── .gitignore ├── SECURITY.md ├── package.json ├── deno.json ├── CONTRIBUTING.md ├── README.md ├── packager.ts ├── CODE_OF_CONDUCT.md └── LICENSE /etc/coverage/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /mod.ts: -------------------------------------------------------------------------------- 1 | export * from "./src/mod.ts"; 2 | -------------------------------------------------------------------------------- /import_map.json: -------------------------------------------------------------------------------- 1 | { 2 | "imports": { 3 | } 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "denoland.vscode-deno", 4 | "ryanluker.vscode-coverage-gutters" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [eserozvataf] 4 | patreon: eserozvataf 5 | open_collective: eser 6 | -------------------------------------------------------------------------------- /src/mod.ts: -------------------------------------------------------------------------------- 1 | export * from "./types.ts"; 2 | export * from "./locales.ts"; 3 | export * from "./parser.ts"; 4 | export * from "./to-date.ts"; 5 | export * from "./to-temporal.ts"; 6 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | interface DateFormat { 2 | weekday?: string; 3 | day?: string; 4 | month?: string; 5 | year?: string; 6 | quarter?: string; 7 | } 8 | 9 | export { type DateFormat }; 10 | -------------------------------------------------------------------------------- /src/polyfill.ts: -------------------------------------------------------------------------------- 1 | import { Temporal } from "https://cdn.skypack.dev/@js-temporal/polyfill"; 2 | 3 | if (!("Temporal" in globalThis)) { 4 | // @ts-ignore: in case of warning 5 | globalThis.Temporal = Temporal; 6 | } 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | root = true 3 | 4 | [*.md] 5 | trim_trailing_whitespace = false 6 | 7 | [*] 8 | indent_style = space 9 | indent_size = 2 10 | end_of_line = lf 11 | charset = utf-8 12 | trim_trailing_whitespace = true 13 | insert_final_newline = true 14 | -------------------------------------------------------------------------------- /src/cli.ts: -------------------------------------------------------------------------------- 1 | import "./polyfill.ts"; 2 | import { parseDate, toDate, toTemporal } from "./mod.ts"; 3 | 4 | const parsedDate = parseDate("07/12/1995", "en-GB"); // { year: 1995, month: 12, day: 7 } 5 | 6 | // new temporal Date API 7 | const temporal = toTemporal(parsedDate!); 8 | console.log(temporal.toString()); // => 1995-12-07 9 | 10 | // old Date API 11 | const date = toDate(parsedDate!); 12 | console.log(date.toString()); // => 1995-12-07T00:00:00 13 | -------------------------------------------------------------------------------- /src/to-temporal.ts: -------------------------------------------------------------------------------- 1 | import { type DateFormat } from "./types.ts"; 2 | // import { Temporal as TemporalPolyfill } from "npm:@js-temporal/polyfill"; 3 | 4 | const toTemporal = function toTemporal(input: DateFormat) { 5 | // const temporal = ("Temporal" in globalThis) 6 | // ? globalThis.Temporal 7 | // : TemporalPolyfill; 8 | 9 | // deno-lint-ignore no-explicit-any 10 | const temporal: any = ("Temporal" in globalThis); 11 | 12 | return temporal.PlainDate.from(input); 13 | }; 14 | 15 | export { toTemporal }; 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # OS-specific files 4 | .DS_Store 5 | Thumbs.db 6 | 7 | # Editor-specific files 8 | .vscode/* 9 | !.vscode/extensions.json 10 | !.vscode/settings.json 11 | .idea/ 12 | 13 | # NPM packaging 14 | node_modules/ 15 | yarn.lock 16 | package-lock.json 17 | 18 | # Build output 19 | dist/ 20 | tsconfig.tsbuildinfo 21 | 22 | # sensitive files 23 | *.pem 24 | *.swp 25 | 26 | # coverage files 27 | etc/coverage/*.json 28 | etc/coverage/cov_profile.lcov 29 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 1.0.x | :white_check_mark: | 11 | | < 0.9 | :x: | 12 | 13 | ## Reporting a Vulnerability 14 | 15 | Use this section to tell people how to report a vulnerability. 16 | 17 | Tell them where to go, how often they can expect to get an update on a reported 18 | vulnerability, what to expect if the vulnerability is accepted or declined, etc. 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /src/to-date.ts: -------------------------------------------------------------------------------- 1 | import { type DateFormat } from "./types.ts"; 2 | 3 | const toDate = function toDate(input: DateFormat): Date { 4 | const now = new Date(); 5 | 6 | const year = (input.year !== undefined) 7 | ? Number(input.year) 8 | : now.getFullYear(); 9 | 10 | let month = (input.month !== undefined) ? Number(input.month) - 1 : 1; 11 | let day = (input.day !== undefined) ? Number(input.day) : 1; 12 | 13 | if (input.quarter !== undefined) { 14 | day = 1; 15 | switch (input.quarter) { 16 | case "1": 17 | month = 0; 18 | break; 19 | case "2": 20 | month = 3; 21 | break; 22 | case "3": 23 | month = 6; 24 | break; 25 | case "4": 26 | month = 9; 27 | break; 28 | } 29 | } 30 | 31 | return new Date(year, month, day); 32 | }; 33 | 34 | export { toDate }; 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "temporal-parse", 3 | "description": "parses human-readable strings for JavaScript's Temporal API", 4 | "keywords": [ 5 | "date", 6 | "datetime", 7 | "parse", 8 | "parser", 9 | "temporal", 10 | "library", 11 | "api", 12 | "human-readable" 13 | ], 14 | "version": "0.0.8", 15 | "homepage": "https://github.com/eserozvataf/temporal-parse#readme", 16 | "author": "Eser Ozvataf ", 17 | "contributors": [ 18 | { 19 | "name": "Eser Ozvataf", 20 | "email": "eser@ozvataf.com", 21 | "url": "http://eser.ozvataf.com/" 22 | } 23 | ], 24 | "repository": { 25 | "type": "git", 26 | "url": "git+https://github.com/eserozvataf/temporal-parse.git" 27 | }, 28 | "bugs": { 29 | "url": "https://github.com/eserozvataf/temporal-parse/issues" 30 | }, 31 | "license": "Apache-2.0", 32 | "exports": { 33 | "./package.json": { 34 | "import": "./esm/package.json", 35 | "require": "./script/package.json" 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/locales/types.ts: -------------------------------------------------------------------------------- 1 | type Months = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; 2 | type Weekdays = 0 | 1 | 2 | 3 | 4 | 5 | 6; 3 | 4 | type MonthNames = { [key in Months]: string[] }; 5 | type WeekdayNames = { [key in Weekdays]: string[] }; 6 | 7 | interface Locale { 8 | code: string; 9 | 10 | isDayPlacedFirst: boolean; 11 | dateDelimiters: string[]; 12 | 13 | dateFormats: { 14 | full?: string; 15 | wide?: string; 16 | long?: string; 17 | short?: string; 18 | [key: number]: string; 19 | }; 20 | timeFormats?: { 21 | full?: string; 22 | wide?: string; 23 | long?: string; 24 | short?: string; 25 | [key: number]: string; 26 | }; 27 | dateTimeFormats?: { 28 | full?: string; 29 | wide?: string; 30 | long?: string; 31 | short?: string; 32 | [key: number]: string; 33 | }; 34 | 35 | monthNames: { 36 | full: MonthNames; 37 | short: MonthNames; 38 | }; 39 | dayNames: { 40 | full: WeekdayNames; 41 | short: WeekdayNames; 42 | }; 43 | } 44 | 45 | export { 46 | type Locale, 47 | type MonthNames, 48 | type Months, 49 | type WeekdayNames, 50 | type Weekdays, 51 | }; 52 | -------------------------------------------------------------------------------- /deno.json: -------------------------------------------------------------------------------- 1 | { 2 | "importMap": "./import_map.json", 3 | "lint": { 4 | "files": { 5 | "include": [ 6 | "src/", 7 | "mod.ts", 8 | "*.md", 9 | "*.json" 10 | ], 11 | "exclude": [ 12 | "dist/", 13 | "node_modules/" 14 | ] 15 | }, 16 | "rules": { 17 | "tags": [ 18 | "recommended" 19 | ], 20 | "include": [], 21 | "exclude": [] 22 | } 23 | }, 24 | "fmt": { 25 | "files": { 26 | "include": [ 27 | "src/", 28 | "mod.ts", 29 | "*.md", 30 | "*.json" 31 | ], 32 | "exclude": [ 33 | "dist/", 34 | "node_modules/" 35 | ] 36 | } 37 | }, 38 | "test": { 39 | "files": { 40 | "include": [ 41 | "src/" 42 | ], 43 | "exclude": [ 44 | "dist/", 45 | "node_modules/" 46 | ] 47 | } 48 | }, 49 | "tasks": { 50 | "test": "deno test ./src/ --allow-net --coverage=./etc/coverage", 51 | "test:coverage": "deno coverage ./etc/coverage", 52 | "test:generate-lcov": "deno coverage ./etc/coverage --lcov > ./etc/coverage/cov_profile.lcov", 53 | "bench": "deno bench ./src/ --unstable", 54 | "cleanup": "rm -rf ./dist/ yarn.lock package-lock.json", 55 | "build": "deno run -A packager.ts", 56 | "pub": "deno task build && npm publish dist/" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [temporal-parse](https://github.com/eserozvataf/temporal-parse) 2 | 3 | 👍🎉 First off, thanks for taking the time to contribute! 🎉👍 4 | 5 | The following is a set of guidelines for contributing to temporal-parse and its packages, which are hosted in GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 6 | 7 | ## What should I know before I get started? 8 | 9 | ### Code of Conduct 10 | 11 | This project and everyone participating in it is governed by the [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [eser@ozvataf.com](mailto:eser@ozvataf.com). 12 | 13 | ### Technical Requirements 14 | 15 | Just JavaScript and Git. 16 | 17 | ### Conventions 18 | 19 | Using Deno Formatter should be fine for now. 20 | 21 | ### Design Decisions 22 | 23 | To make a significant decision in how we maintain the project and what we can or cannot support, please open a new topic as an issue to discuss the suggested design first. 24 | 25 | ## How Can I Contribute? 26 | 27 | It is publicly open for any contribution. Reporting bugs, suggesting enhancements, bugfixes, new features and extra modules are welcome. 28 | 29 | * To contribute to code: Fork the repo, push your changes to your fork, and submit a pull request. 30 | * To report a bug: If something does not work, please report it using [GitHub Issues](https://github.com/eserozvataf/temporal-parse/issues). 31 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "deno.enable": true, 3 | "deno.suggest.autoImports": true, 4 | "deno.suggest.completeFunctionCalls": true, 5 | "deno.suggest.imports.autoDiscover": true, 6 | "deno.suggest.imports.hosts": { 7 | "https://deno.land": true 8 | }, 9 | "deno.suggest.names": true, 10 | "deno.suggest.paths": true, 11 | "deno.unstable": true, 12 | "editor.defaultFormatter": "denoland.vscode-deno", 13 | "coverage-gutters.coverageBaseDir": "**/etc/coverage", 14 | "coverage-gutters.coverageFileNames": [ "cov_profile.lcov" ], 15 | "coverage-gutters.showGutterCoverage": true, 16 | "coverage-gutters.showLineCoverage": true, 17 | "coverage-gutters.showRulerCoverage": true, 18 | "files.exclude": { 19 | "**/.git": true, 20 | "**/.svn": true, 21 | "**/.hg": true, 22 | "**/CVS": true, 23 | "**/.DS_Store": true, 24 | "**/Thumbs.db": true, 25 | ".github/ISSUE_TEMPLATE": true, 26 | ".github/FUNDING.yml": true, 27 | "etc/coverage/*.json": true, 28 | "node_modules": true, 29 | "yarn.lock": true, 30 | "package-lock.json": true, 31 | "package.json": true, 32 | ".editorconfig": true, 33 | "CODE_OF_CONDUCT.md": true, 34 | "CONTRIBUTING.md": true, 35 | "SECURITY.md": true, 36 | "LICENSE": true, 37 | "packager.ts": true 38 | }, 39 | "files.watcherExclude": { 40 | "**/.git/objects/**": true, 41 | "**/.git/subtree-cache/**": true, 42 | "**/node_modules/*/**": true, 43 | "**/.hg/store/**": true, 44 | "dist/**": true, 45 | "etc/coverage/**": true 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/locales.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./locales/types.ts"; 2 | import { combineLocales } from "./locales/combiners.ts"; 3 | import { locale as genericEuropeAsia } from "./locales/generic-europe-asia.ts"; 4 | import { locale as genericAmerican } from "./locales/generic-american.ts"; 5 | import { locale as enUS } from "./locales/en-US.ts"; 6 | import { locale as enGB } from "./locales/en-GB.ts"; 7 | import { locale as deDE } from "./locales/de-DE.ts"; 8 | import { locale as frFR } from "./locales/fr-FR.ts"; 9 | import { locale as itIT } from "./locales/it-IT.ts"; 10 | import { locale as esES } from "./locales/es-ES.ts"; 11 | import { locale as trTR } from "./locales/tr-TR.ts"; 12 | 13 | type SupportedLocales = 14 | | "generic-europe-asia" 15 | | "generic-american" 16 | | "en-US" 17 | | "en-GB" 18 | | "de-DE" 19 | | "fr-FR" 20 | | "it-IT" 21 | | "es-ES" 22 | | "tr-TR"; 23 | 24 | const locales: Record = { 25 | "generic-europe-asia": genericEuropeAsia, 26 | "generic-american": genericAmerican, 27 | "en-US": enUS, 28 | "en-GB": enGB, 29 | "de-DE": deDE, 30 | "fr-FR": frFR, 31 | "it-IT": itIT, 32 | "es-ES": esES, 33 | "tr-TR": trTR, 34 | }; 35 | 36 | const combineKnownLocales = function combineKnownLocales( 37 | code: string, 38 | ...targetLocales: SupportedLocales[] 39 | ): Locale { 40 | return combineLocales( 41 | code, 42 | ...targetLocales.map((targetLocale) => locales[targetLocale]), 43 | ); 44 | }; 45 | 46 | export { 47 | combineKnownLocales, 48 | combineLocales, 49 | type Locale, 50 | locales, 51 | type SupportedLocales, 52 | }; 53 | -------------------------------------------------------------------------------- /src/locales/tr-TR.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | 3 | const locale: Locale = { 4 | code: "tr-TR", 5 | 6 | isDayPlacedFirst: true, 7 | dateDelimiters: [".", "/", "-"], 8 | 9 | dateFormats: { 10 | full: "d MMMM y EEEE", 11 | wide: "d MMMM y", 12 | long: "d MMM y", 13 | short: "dd.MM.yyyy", 14 | }, 15 | timeFormats: { 16 | full: "HH:mm:ss zzzz", 17 | wide: "HH:mm:ss z", 18 | long: "HH:mm:ss", 19 | short: "HH:mm", 20 | }, 21 | dateTimeFormats: { 22 | full: "{{date}} 'saat' {{time}}", 23 | wide: "{{date}} 'saat' {{time}}", 24 | long: "{{date}}, {{time}}", 25 | short: "{{date}}, {{time}}", 26 | }, 27 | 28 | monthNames: { 29 | full: { 30 | 1: ["Ocak"], 31 | 2: ["Şubat"], 32 | 3: ["Mart"], 33 | 4: ["Nisan"], 34 | 5: ["Mayıs"], 35 | 6: ["Haziran"], 36 | 7: ["Temmuz"], 37 | 8: ["Ağustos"], 38 | 9: ["Eylül"], 39 | 10: ["Ekim"], 40 | 11: ["Kasım"], 41 | 12: ["Aralık"], 42 | }, 43 | short: { 44 | 1: ["Oca"], 45 | 2: ["Şub"], 46 | 3: ["Mar"], 47 | 4: ["Nis"], 48 | 5: ["May"], 49 | 6: ["Haz"], 50 | 7: ["Tem"], 51 | 8: ["Ağu"], 52 | 9: ["Eyl"], 53 | 10: ["Eki"], 54 | 11: ["Kas"], 55 | 12: ["Ara"], 56 | }, 57 | }, 58 | dayNames: { 59 | full: { 60 | 0: ["Pazar"], 61 | 1: ["Pazartesi"], 62 | 2: ["Salı"], 63 | 3: ["Çarşamba"], 64 | 4: ["Perşembe"], 65 | 5: ["Cuma"], 66 | 6: ["Cumartesi"], 67 | }, 68 | short: { 69 | 0: ["Paz"], 70 | 1: ["Pzt"], 71 | 2: ["Sal"], 72 | 3: ["Çar"], 73 | 4: ["Per"], 74 | 5: ["Cum"], 75 | 6: ["Cmt"], 76 | }, 77 | }, 78 | }; 79 | 80 | export { locale }; 81 | -------------------------------------------------------------------------------- /src/locales/fr-FR.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | 3 | const locale: Locale = { 4 | code: "fr-FR", 5 | 6 | isDayPlacedFirst: true, 7 | dateDelimiters: ["/", ".", "-"], 8 | 9 | dateFormats: { 10 | full: "EEEE d MMMM y", 11 | wide: "d MMMM y", 12 | long: "d MMM y", 13 | short: "dd/MM/y", 14 | }, 15 | timeFormats: { 16 | full: "HH:mm:ss zzzz", 17 | wide: "HH:mm:ss a z", 18 | long: "HH:mm:ss", 19 | short: "HH:mm", 20 | }, 21 | dateTimeFormats: { 22 | full: "{{date}} 'à' {{time}}", 23 | wide: "{{date}} 'à' {{time}}", 24 | long: "{{date}}, {{time}}", 25 | short: "{{date}}, {{time}}", 26 | }, 27 | 28 | monthNames: { 29 | full: { 30 | 1: ["Janvier"], 31 | 2: ["Février"], 32 | 3: ["Mars"], 33 | 4: ["Avril"], 34 | 5: ["Mai"], 35 | 6: ["Juin"], 36 | 7: ["Juillet"], 37 | 8: ["Août"], 38 | 9: ["Septembre"], 39 | 10: ["Octobre"], 40 | 11: ["Novembre"], 41 | 12: ["Décembre"], 42 | }, 43 | short: { 44 | 1: ["Jan"], 45 | 2: ["Fév"], 46 | 3: ["Mar"], 47 | 4: ["Avr"], 48 | 5: ["Mai"], 49 | 6: ["Jun"], 50 | 7: ["Jul"], 51 | 8: ["Aoû"], 52 | 9: ["Sep"], 53 | 10: ["Oct"], 54 | 11: ["Nov"], 55 | 12: ["Déc"], 56 | }, 57 | }, 58 | dayNames: { 59 | full: { 60 | 0: ["Dimanche"], 61 | 1: ["Lundi"], 62 | 2: ["Mardi"], 63 | 3: ["Mercredi"], 64 | 4: ["Jeudi"], 65 | 5: ["Vendredi"], 66 | 6: ["Samedi"], 67 | }, 68 | short: { 69 | 0: ["Dim"], 70 | 1: ["Lun"], 71 | 2: ["Mar"], 72 | 3: ["Mer"], 73 | 4: ["Jeu"], 74 | 5: ["Ven"], 75 | 6: ["Sam"], 76 | }, 77 | }, 78 | }; 79 | 80 | export { locale }; 81 | -------------------------------------------------------------------------------- /src/locales/it-IT.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | 3 | const locale: Locale = { 4 | code: "it-IT", 5 | 6 | isDayPlacedFirst: true, 7 | dateDelimiters: ["/", ".", "-"], 8 | 9 | dateFormats: { 10 | full: "EEEE d MMMM y", 11 | wide: "d MMMM y", 12 | long: "d MMM y", 13 | short: "dd/MM/y", 14 | }, 15 | timeFormats: { 16 | full: "HH:mm:ss zzzz", 17 | wide: "HH:mm:ss z", 18 | long: "HH:mm:ss", 19 | short: "HH:mm", 20 | }, 21 | dateTimeFormats: { 22 | full: "{{date}} {{time}}", 23 | wide: "{{date}} {{time}}", 24 | long: "{{date}} {{time}}", 25 | short: "{{date}} {{time}}", 26 | }, 27 | 28 | monthNames: { 29 | full: { 30 | 1: ["Gennaio"], 31 | 2: ["Febbraio"], 32 | 3: ["Marzo"], 33 | 4: ["Aprile"], 34 | 5: ["Maggio"], 35 | 6: ["Giugno"], 36 | 7: ["Luglio"], 37 | 8: ["Agosto"], 38 | 9: ["Settembre"], 39 | 10: ["Ottobre"], 40 | 11: ["Novembre"], 41 | 12: ["Dicembre"], 42 | }, 43 | short: { 44 | 1: ["Gen"], 45 | 2: ["Feb"], 46 | 3: ["Mar"], 47 | 4: ["Apr"], 48 | 5: ["Mag"], 49 | 6: ["Giu"], 50 | 7: ["Lug"], 51 | 8: ["Ago"], 52 | 9: ["Set"], 53 | 10: ["Ott"], 54 | 11: ["Nov"], 55 | 12: ["Dic"], 56 | }, 57 | }, 58 | dayNames: { 59 | full: { 60 | 0: ["Domenica"], 61 | 1: ["Lunedì"], 62 | 2: ["Martedì"], 63 | 3: ["Mercoledì"], 64 | 4: ["Giovedì"], 65 | 5: ["Venerdì"], 66 | 6: ["Sabato"], 67 | }, 68 | short: { 69 | 0: ["Dom"], 70 | 1: ["Lun"], 71 | 2: ["Mar"], 72 | 3: ["Mer"], 73 | 4: ["Gio"], 74 | 5: ["Ven"], 75 | 6: ["Sab"], 76 | }, 77 | }, 78 | }; 79 | 80 | export { locale }; 81 | -------------------------------------------------------------------------------- /src/locales/de-DE.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | 3 | const locale: Locale = { 4 | code: "de-DE", 5 | 6 | isDayPlacedFirst: true, 7 | dateDelimiters: [".", "/", "-"], 8 | 9 | dateFormats: { 10 | full: "EEEE, do MMMM y", 11 | wide: "do MMMM y", 12 | long: "do MMM y", 13 | short: "dd.MM.y", 14 | }, 15 | timeFormats: { 16 | full: "HH:mm:ss zzzz", 17 | wide: "HH:mm:ss a z", 18 | long: "HH:mm:ss", 19 | short: "HH:mm", 20 | }, 21 | dateTimeFormats: { 22 | full: "{{date}} 'um' {{time}}", 23 | wide: "{{date}} 'um' {{time}}", 24 | long: "{{date}} {{time}}", 25 | short: "{{date}} {{time}}", 26 | }, 27 | 28 | monthNames: { 29 | full: { 30 | 1: ["Januar"], 31 | 2: ["Februar"], 32 | 3: ["März"], 33 | 4: ["April"], 34 | 5: ["Mai"], 35 | 6: ["Juni"], 36 | 7: ["Juli"], 37 | 8: ["August"], 38 | 9: ["September"], 39 | 10: ["Oktober"], 40 | 11: ["November"], 41 | 12: ["Dezember"], 42 | }, 43 | short: { 44 | 1: ["Jan"], 45 | 2: ["Feb"], 46 | 3: ["Mär"], 47 | 4: ["Apr"], 48 | 5: ["Mai"], 49 | 6: ["Jun"], 50 | 7: ["Jul"], 51 | 8: ["Aug"], 52 | 9: ["Sep"], 53 | 10: ["Okt"], 54 | 11: ["Nov"], 55 | 12: ["Dez"], 56 | }, 57 | }, 58 | 59 | dayNames: { 60 | full: { 61 | 0: ["Sonntag"], 62 | 1: ["Montag"], 63 | 2: ["Dienstag"], 64 | 3: ["Mittwoch"], 65 | 4: ["Donnerstag"], 66 | 5: ["Freitag"], 67 | 6: ["Samstag"], 68 | }, 69 | short: { 70 | 0: ["So"], 71 | 1: ["Mo"], 72 | 2: ["Di"], 73 | 3: ["Mi"], 74 | 4: ["Do"], 75 | 5: ["Fr"], 76 | 6: ["Sa"], 77 | }, 78 | }, 79 | }; 80 | 81 | export { locale }; 82 | -------------------------------------------------------------------------------- /src/locales/en-GB.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | 3 | const locale: Locale = { 4 | code: "en-GB", 5 | 6 | isDayPlacedFirst: true, 7 | dateDelimiters: ["/", ".", "-"], 8 | 9 | dateFormats: { 10 | full: "EEEE, d MMMM yyyy", 11 | wide: "d MMMM yyyy", 12 | long: "d MMM yyyy", 13 | short: "dd/MM/yyyy", 14 | }, 15 | timeFormats: { 16 | full: "HH:mm:ss zzzz", 17 | wide: "HH:mm:ss a z", 18 | long: "HH:mm:ss", 19 | short: "HH:mm", 20 | }, 21 | dateTimeFormats: { 22 | full: "{{date}} 'at' {{time}}", 23 | wide: "{{date}} 'at' {{time}}", 24 | long: "{{date}}, {{time}}", 25 | short: "{{date}}, {{time}}", 26 | }, 27 | 28 | monthNames: { 29 | full: { 30 | 1: ["January"], 31 | 2: ["February"], 32 | 3: ["March"], 33 | 4: ["April"], 34 | 5: ["May"], 35 | 6: ["June"], 36 | 7: ["July"], 37 | 8: ["August"], 38 | 9: ["September"], 39 | 10: ["October"], 40 | 11: ["November"], 41 | 12: ["December"], 42 | }, 43 | short: { 44 | 1: ["Jan"], 45 | 2: ["Feb"], 46 | 3: ["Mar"], 47 | 4: ["Apr"], 48 | 5: ["May"], 49 | 6: ["Jun"], 50 | 7: ["Jul"], 51 | 8: ["Aug"], 52 | 9: ["Sep"], 53 | 10: ["Oct"], 54 | 11: ["Nov"], 55 | 12: ["Dec"], 56 | }, 57 | }, 58 | dayNames: { 59 | full: { 60 | 0: ["Sunday"], 61 | 1: ["Monday"], 62 | 2: ["Tuesday"], 63 | 3: ["Wednesday"], 64 | 4: ["Thursday"], 65 | 5: ["Friday"], 66 | 6: ["Saturday"], 67 | }, 68 | short: { 69 | 0: ["Sun"], 70 | 1: ["Mon"], 71 | 2: ["Tue"], 72 | 3: ["Wed"], 73 | 4: ["Thu"], 74 | 5: ["Fri"], 75 | 6: ["Sat"], 76 | }, 77 | }, 78 | }; 79 | 80 | export { locale }; 81 | -------------------------------------------------------------------------------- /src/locales/en-US.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | 3 | const locale: Locale = { 4 | code: "en-US", 5 | 6 | isDayPlacedFirst: false, 7 | dateDelimiters: ["/", ".", "-"], 8 | 9 | dateFormats: { 10 | full: "EEEE, MMMM do, y", 11 | wide: "MMMM do, y", 12 | long: "MMM d, y", 13 | short: "MM/dd/yyyy", 14 | }, 15 | timeFormats: { 16 | full: "h:mm:ss a zzzz", 17 | wide: "h:mm:ss a z", 18 | long: "h:mm:ss a", 19 | short: "h:mm a", 20 | }, 21 | dateTimeFormats: { 22 | full: "{{date}} 'at' {{time}}", 23 | wide: "{{date}} 'at' {{time}}", 24 | long: "{{date}}, {{time}}", 25 | short: "{{date}}, {{time}}", 26 | }, 27 | 28 | monthNames: { 29 | full: { 30 | 1: ["January"], 31 | 2: ["February"], 32 | 3: ["March"], 33 | 4: ["April"], 34 | 5: ["May"], 35 | 6: ["June"], 36 | 7: ["July"], 37 | 8: ["August"], 38 | 9: ["September"], 39 | 10: ["October"], 40 | 11: ["November"], 41 | 12: ["December"], 42 | }, 43 | short: { 44 | 1: ["Jan"], 45 | 2: ["Feb"], 46 | 3: ["Mar"], 47 | 4: ["Apr"], 48 | 5: ["May"], 49 | 6: ["Jun"], 50 | 7: ["Jul"], 51 | 8: ["Aug"], 52 | 9: ["Sep"], 53 | 10: ["Oct"], 54 | 11: ["Nov"], 55 | 12: ["Dec"], 56 | }, 57 | }, 58 | dayNames: { 59 | full: { 60 | 0: ["Sunday"], 61 | 1: ["Monday"], 62 | 2: ["Tuesday"], 63 | 3: ["Wednesday"], 64 | 4: ["Thursday"], 65 | 5: ["Friday"], 66 | 6: ["Saturday"], 67 | }, 68 | short: { 69 | 0: ["Sun"], 70 | 1: ["Mon"], 71 | 2: ["Tue"], 72 | 3: ["Wed"], 73 | 4: ["Thu"], 74 | 5: ["Fri"], 75 | 6: ["Sat"], 76 | }, 77 | }, 78 | }; 79 | 80 | export { locale }; 81 | -------------------------------------------------------------------------------- /src/locales/es-ES.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | 3 | const locale: Locale = { 4 | code: "es-ES", 5 | 6 | isDayPlacedFirst: true, 7 | dateDelimiters: ["/", ".", "-"], 8 | 9 | dateFormats: { 10 | full: "EEEE, d 'de' MMMM 'de' y", 11 | wide: "d 'de' MMMM 'de' y", 12 | long: "d MMM y", 13 | short: "dd/MM/y", 14 | }, 15 | timeFormats: { 16 | full: "HH:mm:ss zzzz", 17 | wide: "HH:mm:ss a z", 18 | long: "HH:mm:ss", 19 | short: "HH:mm", 20 | }, 21 | dateTimeFormats: { 22 | full: "{{date}} 'a las' {{time}}", 23 | wide: "{{date}} 'a las' {{time}}", 24 | long: "{{date}}, {{time}}", 25 | short: "{{date}}, {{time}}", 26 | }, 27 | 28 | monthNames: { 29 | full: { 30 | 1: ["Enero"], 31 | 2: ["Febrero"], 32 | 3: ["Marzo"], 33 | 4: ["Abril"], 34 | 5: ["Mayo"], 35 | 6: ["Junio"], 36 | 7: ["Julio"], 37 | 8: ["Agosto"], 38 | 9: ["Septiembre"], 39 | 10: ["Octubre"], 40 | 11: ["Noviembre"], 41 | 12: ["Diciembre"], 42 | }, 43 | short: { 44 | 1: ["Ene"], 45 | 2: ["Feb"], 46 | 3: ["Mar"], 47 | 4: ["Abr"], 48 | 5: ["May"], 49 | 6: ["Jun"], 50 | 7: ["Jul"], 51 | 8: ["Ago"], 52 | 9: ["Sep"], 53 | 10: ["Oct"], 54 | 11: ["Nov"], 55 | 12: ["Dic"], 56 | }, 57 | }, 58 | dayNames: { 59 | full: { 60 | 0: ["Domingo"], 61 | 1: ["Lunes"], 62 | 2: ["Martes"], 63 | 3: ["Miércoles"], 64 | 4: ["Jueves"], 65 | 5: ["Viernes"], 66 | 6: ["Sábado"], 67 | }, 68 | short: { 69 | 0: ["Dom"], 70 | 1: ["Lun"], 71 | 2: ["Mar"], 72 | 3: ["Mié"], 73 | 4: ["Jue"], 74 | 5: ["Vie"], 75 | 6: ["Sáb"], 76 | }, 77 | }, 78 | }; 79 | 80 | export { locale }; 81 | -------------------------------------------------------------------------------- /src/date-tokenizer.test.ts: -------------------------------------------------------------------------------- 1 | import * as asserts from "https://deno.land/std@0.154.0/testing/asserts.ts"; 2 | import { dateSamplesEA, dateSamplesUS } from "./sample-dates.ts"; 3 | import { DateTokenType, tokenizeDate } from "./date-tokenizer.ts"; 4 | import { combineKnownLocales, parseDate, toDate } from "./mod.ts"; 5 | 6 | Deno.test(function tokenizeDateTest() { 7 | dateSamplesEA.forEach((date) => { 8 | const tokenized = tokenizeDate(date); 9 | 10 | asserts.assert(tokenized.length > 0, `Date "${date}" is not valid`); 11 | asserts.assertEquals( 12 | tokenized.findIndex((x) => x[0] === DateTokenType.unknown), 13 | -1, 14 | `Date "${date}" is not valid`, 15 | ); 16 | }); 17 | }); 18 | 19 | Deno.test(function falseValues() { 20 | const parsedDate = parseDate("not a date", "generic-europe-asia"); 21 | 22 | asserts.assertEquals(parsedDate, undefined); 23 | }); 24 | 25 | Deno.test(function dateComparision() { 26 | for (let i = 0; i < dateSamplesEA.length; i++) { 27 | const dateEA = dateSamplesEA[i]; 28 | const dateEAParsed = parseDate(dateEA, "generic-europe-asia"); 29 | 30 | const dateUS = dateSamplesUS[i]; 31 | const dateUSParsed = parseDate(dateUS, "generic-american"); 32 | 33 | // console.log( 34 | // `dateEA: ${dateEA}, dateUS: ${dateUS}`, 35 | // dateEAParsed, 36 | // dateUSParsed, 37 | // ); 38 | asserts.assertEquals( 39 | toDate(dateEAParsed!), 40 | toDate(dateUSParsed!), 41 | // `dateEA: ${dateEA}, dateUS: ${dateUS}`, 42 | ); 43 | } 44 | }); 45 | 46 | Deno.test(function localeCombination() { 47 | const combinedLocale = combineKnownLocales( 48 | "en-GB+tr-TR", 49 | "en-GB", 50 | "tr-TR", 51 | ); 52 | 53 | const dateTR = "12 Ağustos 2022"; 54 | const dateTRParsed = parseDate(dateTR, combinedLocale); 55 | 56 | const dateGB = "12 August 2022"; 57 | const dateGBParsed = parseDate(dateGB, combinedLocale); 58 | 59 | asserts.assertEquals( 60 | toDate(dateTRParsed!), 61 | toDate(dateGBParsed!), 62 | // `dateTR: ${dateTR}, dateGB: ${dateGB}`, 63 | ); 64 | }); 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🕑 [temporal-parse](https://github.com/eserozvataf/temporal-parse) 2 | 3 | [![npm version][npm-image]][npm-url] 4 | [![npm download][npm-download-image]][npm-url] 5 | [![license][license-image]][license-url] 6 | 7 | 8 | ## What is the temporal-parse? 9 | 10 | `Temporal` is the next generation of JavaScript's standard Date API. It's currently proposed to TC39 (see: https://github.com/tc39/proposal-temporal) and in Stage 3. 11 | 12 | However Temporal brings many features, there'll be no "human-readable string format parsing". (see: https://tc39.es/proposal-temporal/docs/strings.html) 13 | 14 | This project aims to parse human-readable strings for Temporal, and generate proper inputs for Temporal's `Temporal.xxxx.from()` functions. 15 | 16 | 17 | ## Sample Usage 18 | 19 | ```js 20 | import "npm:temporal-parse/polyfill"; 21 | import { parseDate, toDate, toTemporal } from "npm:temporal-parse"; 22 | 23 | const parsedDate = parseDate("07/12/1995", "en-GB"); // { year: 1995, month: 12, day: 7 } 24 | 25 | // new temporal Date API 26 | const temporal = toTemporal(parsedDate); 27 | console.log(temporal.toString()); // => 1995-12-07 28 | 29 | // old Date API 30 | const date = toDate(parsedDate); 31 | console.log(date.toString()); // => 1995-12-07T00:00:00 32 | ``` 33 | 34 | 35 | ## License 36 | 37 | Apache 2.0, for further details, please see [LICENSE](LICENSE) file 38 | 39 | 40 | ## Contributing 41 | 42 | See [contributors.md](contributors.md) 43 | 44 | It is publicly open for any contribution. Bugfixes, new features and extra 45 | modules are welcome. 46 | 47 | - To contribute to code: Fork the repo, push your changes to your fork, and 48 | submit a pull request. 49 | - To report a bug: If something does not work, please report it using 50 | [GitHub Issues](https://github.com/eserozvataf/temporal-parse/issues). 51 | 52 | 53 | ## To Support 54 | 55 | [Visit my GitHub Sponsors profile at github.com/sponsors/eserozvataf](https://github.com/sponsors/eserozvataf) 56 | 57 | [npm-image]: https://img.shields.io/npm/v/temporal-parse.svg?style=flat-square 58 | [npm-download-image]: https://img.shields.io/npm/dt/temporal-parse.svg?style=flat-square 59 | [npm-url]: https://www.npmjs.com/package/temporal-parse 60 | [license-image]: https://img.shields.io/npm/l/temporal-parse.svg?style=flat-square 61 | [license-url]: https://github.com/eserozvataf/temporal-parse/blob/master/LICENSE 62 | -------------------------------------------------------------------------------- /packager.ts: -------------------------------------------------------------------------------- 1 | import { build, emptyDir } from "https://deno.land/x/dnt/mod.ts"; 2 | import packageJson from "./package.json" assert { type: "json" }; 3 | import denoJson from "./deno.json" assert { type: "json" }; 4 | 5 | await emptyDir("./dist"); 6 | 7 | await build({ 8 | // packageManager: "yarn", 9 | entryPoints: [ 10 | "./src/mod.ts", 11 | { 12 | name: "./polyfill", 13 | path: "./src/polyfill.ts", 14 | }, 15 | ], 16 | outDir: "./dist", 17 | package: packageJson, 18 | importMap: denoJson.importMap, 19 | shims: { 20 | // see JS docs for overview and more options 21 | deno: false, 22 | // replaces node.js timers with browser-API compatible ones 23 | timers: false, 24 | // the global confirm, alert, and prompt functions 25 | prompts: false, 26 | // shims the Blob global with the one from the "buffer" module 27 | blob: false, 28 | // shims the crypto global. 29 | crypto: false, 30 | // shims DOMException 31 | domException: false, 32 | // shims fetch, File, FormData, Headers, Request, and Response 33 | undici: false, 34 | // shams (checker) for the global.WeakRef, helps type-checking only 35 | weakRef: false, 36 | // shims WebSocket 37 | webSocket: false, 38 | }, 39 | mappings: { 40 | "https://cdn.skypack.dev/@js-temporal/polyfill": { 41 | name: "@js-temporal/polyfill", 42 | version: "0.4.2", 43 | peerDependency: false, 44 | }, 45 | }, 46 | typeCheck: true, 47 | test: false, 48 | declaration: true, 49 | compilerOptions: { 50 | // importHelpers: tsconfigJson?.compilerOptions?.importHelpers, 51 | importHelpers: false, 52 | // target: tsconfigJson?.compilerOptions?.target, 53 | target: "ES2017", 54 | // sourceMap: tscconfigJson?.compilerOptions?.sourceMap, 55 | // inlineSources: tscconfigJson?.compilerOptions?.inlineSources, 56 | // lib: denoJson?.compilerOptions?.lib as LibName[] | undefined, 57 | lib: ["esnext", "dom", "dom.iterable"], // , "dom.asynciterable" 58 | // skipLibCheck: tsconfigJson?.compilerOptions?.skipLibCheck, 59 | }, 60 | scriptModule: "cjs", 61 | }); 62 | 63 | // post build steps 64 | Deno.copyFileSync("LICENSE", "dist/LICENSE"); 65 | Deno.copyFileSync("README.md", "dist/README.md"); 66 | Deno.copyFileSync("CODE_OF_CONDUCT.md", "dist/CODE_OF_CONDUCT.md"); 67 | Deno.copyFileSync("CONTRIBUTING.md", "dist/CONTRIBUTING.md"); 68 | Deno.copyFileSync("SECURITY.md", "dist/SECURITY.md"); 69 | -------------------------------------------------------------------------------- /src/locales/combiners.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type Locale, 3 | type MonthNames, 4 | type Months, 5 | type WeekdayNames, 6 | type Weekdays, 7 | } from "./types.ts"; 8 | 9 | const combineFormats = function combineFormats( 10 | ...formats: (Record | undefined)[] 11 | ) { 12 | const result: Record = {}; 13 | let i = 0; 14 | 15 | for (const formatDictionary of formats) { 16 | if (formatDictionary === undefined) { 17 | continue; 18 | } 19 | 20 | for (const [formatKey, formatString] of Object.entries(formatDictionary)) { 21 | if (formatKey in result) { 22 | result[i++] = formatString; 23 | continue; 24 | } 25 | 26 | result[formatKey] = formatString; 27 | } 28 | } 29 | 30 | return result; 31 | }; 32 | 33 | const combineMonthNames = function combineMonthNames( 34 | format: "full" | "short", 35 | ...locales: Locale[] 36 | ): MonthNames { 37 | const monthNames: Partial = {}; 38 | 39 | for (let i = 1; i <= 12; i++) { 40 | monthNames[ i] = locales.flatMap((locale) => 41 | locale.monthNames[format][ i] 42 | ); 43 | } 44 | 45 | return monthNames; 46 | }; 47 | 48 | const combineWeekdayNames = function combineWeekdayNames( 49 | format: "full" | "short", 50 | ...locales: Locale[] 51 | ): WeekdayNames { 52 | const dayNames: Partial = {}; 53 | 54 | for (let i = 0; i <= 6; i++) { 55 | dayNames[ i] = locales.flatMap((locale) => 56 | locale.dayNames[format][ i] 57 | ); 58 | } 59 | 60 | return dayNames; 61 | }; 62 | 63 | const combineLocales = function combineLocales( 64 | code: string, 65 | ...locales: Locale[] 66 | ): Locale { 67 | return { 68 | code: code, 69 | isDayPlacedFirst: locales[0]!.isDayPlacedFirst, 70 | dateDelimiters: locales[0]!.dateDelimiters, 71 | dateFormats: combineFormats(...locales.map((locale) => locale.dateFormats)), 72 | timeFormats: combineFormats(...locales.map((locale) => locale.timeFormats)), 73 | dateTimeFormats: combineFormats( 74 | ...locales.map((locale) => locale.dateTimeFormats), 75 | ), 76 | monthNames: { 77 | full: combineMonthNames("full", ...locales), 78 | short: combineMonthNames("short", ...locales), 79 | }, 80 | dayNames: { 81 | full: combineWeekdayNames("full", ...locales), 82 | short: combineWeekdayNames("short", ...locales), 83 | }, 84 | }; 85 | }; 86 | 87 | export { combineLocales, combineMonthNames, combineWeekdayNames }; 88 | -------------------------------------------------------------------------------- /src/locales/generic-american.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | import { locale as enUS } from "./en-US.ts"; 3 | // import { locale as enGB } from "./en-GB.ts"; 4 | // import { locale as deDE } from "./de-DE.ts"; 5 | // import { locale as frFR } from "./fr-FR.ts"; 6 | // import { locale as itIT } from "./it-IT.ts"; 7 | // import { locale as esES } from "./es-ES.ts"; 8 | // import { locale as trTR } from "./tr-TR.ts"; 9 | 10 | let i = 0; 11 | 12 | const locale: Locale = { 13 | code: "generic-american", 14 | 15 | isDayPlacedFirst: false, 16 | dateDelimiters: ["/", ".", "-"], 17 | 18 | dateFormats: { 19 | ...enUS.dateFormats, 20 | [++i]: "yyyy/M/d", 21 | [++i]: "M/d/yyyy", 22 | [++i]: "M/yyyy", 23 | [++i]: "yyyy/M", 24 | // ---- 25 | [++i]: "yyyy-M-d", 26 | [++i]: "M-d-yyyy", 27 | [++i]: "MMM-d-yyyy", 28 | [++i]: "MMMM-d-yyyy", 29 | [++i]: "M-yyyy", 30 | [++i]: "yyyy-M", 31 | // ---- 32 | [++i]: "yyyy.M.dd", 33 | [++i]: "M.d.yyyy", 34 | [++i]: "MMM.d.yyyy", 35 | [++i]: "MMMM.d.yyyy", 36 | [++i]: "M.yyyy", 37 | [++i]: "yyyy.M", 38 | // ---- 39 | [++i]: "yyyy M d", 40 | [++i]: "M d yyyy", 41 | [++i]: "MMM d yyyy", 42 | [++i]: "MMMM d yyyy", 43 | [++i]: "M yyyy", 44 | [++i]: "yyyy M", 45 | // ---- 46 | [++i]: "M, d, yyyy", 47 | [++i]: "MMM, d, yyyy", 48 | [++i]: "MMMM, d, yyyy", 49 | // ---- 50 | [++i]: "MMM d", 51 | [++i]: "MMMM d", 52 | // ---- 53 | [++i]: "d MMM", 54 | [++i]: "d MMMM", 55 | // ---- 56 | [++i]: "d-MMM", 57 | [++i]: "d-MMMM", 58 | // ---- 59 | [++i]: "MMM yyyy", 60 | [++i]: "MMMM yyyy", 61 | // ---- 62 | [++i]: "yyyy MMM d", 63 | [++i]: "yyyy MMMM d", 64 | // ---- 65 | [++i]: "M/d", 66 | [++i]: "MMM-d", 67 | [++i]: "MMMM, d", 68 | [++i]: "MMMM d, yyyy", 69 | [++i]: "MMMM, yyyy", 70 | // ---- 71 | [++i]: "qq yyyy", 72 | [++i]: "yyyy qq", 73 | [++i]: "EE, d MMMM yyyy", 74 | // ---- 75 | [++i]: "d MMM yyyy", 76 | [++i]: "d MMMM yyyy", 77 | [++i]: "d-MMM-yyyy", 78 | [++i]: "d-MMMM-yyyy", 79 | // ---- extended: will be removed in the future 80 | [++i]: "dd/MMMM/yyyy", 81 | [++i]: "dd/MMM/yyyy", 82 | [++i]: "d/MMMM/yyyy", 83 | [++i]: "d/MMM/yyyy", 84 | [++i]: "MMMM dd yyyy", 85 | [++i]: "MMMM d yyyy", 86 | [++i]: "MMMM/dd/yyyy", 87 | [++i]: "MMMM/d/yyyy", 88 | [++i]: "MMMM.dd.yyyy", 89 | [++i]: "MMMM.d.yyyy", 90 | [++i]: "MMMM-dd-yyyy", 91 | [++i]: "MMMM-d-yyyy", 92 | [++i]: "MMMM.yyyy", 93 | [++i]: "MMMM-yyyy", 94 | [++i]: "MMM/yyyy", 95 | [++i]: "MMM.yyyy", 96 | [++i]: "MMM-yyyy", 97 | [++i]: "MMM/yy", 98 | [++i]: "MMM.yy", 99 | [++i]: "yyyy MMM", 100 | [++i]: "yyyy/MMM", 101 | [++i]: "yyyy.MMM", 102 | [++i]: "yyyy-MMM", 103 | [++i]: "dd/MMM", 104 | [++i]: "dd.MMM", 105 | [++i]: "qq/yyyy", 106 | [++i]: "qq.yyyy", 107 | [++i]: "qq-yyyy", 108 | 109 | [++i]: "d.MMMM.yyyy", 110 | }, 111 | timeFormats: enUS.timeFormats, 112 | dateTimeFormats: enUS.dateTimeFormats, 113 | 114 | monthNames: enUS.monthNames, 115 | dayNames: enUS.dayNames, 116 | }; 117 | 118 | export { locale }; 119 | -------------------------------------------------------------------------------- /src/date-tokenizer.ts: -------------------------------------------------------------------------------- 1 | const enum DateTokenType { 2 | unknown = 0, 3 | initial = 1, 4 | whitespace = 2, 5 | delimiter = 3, 6 | numeric = 4, 7 | alphanumeric = 5, 8 | } 9 | 10 | interface DateToken { 11 | length: 2; 12 | 0: DateTokenType; 13 | 1: string; 14 | } 15 | 16 | const isWhitespace = function isWhitespace(code: number): boolean { 17 | // " " 18 | return (code === 32); 19 | }; 20 | 21 | const isDelimiter = function isDelimiter(code: number): boolean { 22 | // ",", "-", ".", "/" 23 | return (code === 44 || code === 45 || code === 46 || code === 47); 24 | }; 25 | 26 | // const isAlphaCode = function isAlphaCode(code: number): boolean { 27 | // if ( 28 | // // (code > 47 && code < 58) || // numeric (0-9) 29 | // (code > 64 && code < 91) || // upper alpha (A-Z) 30 | // (code > 96 && code < 123) // lower alpha (a-z) 31 | // ) { 32 | // return true; 33 | // } 34 | 35 | // return false; 36 | // }; 37 | 38 | const isNumericCode = function isNumeric(code: number): boolean { 39 | return (code > 47 && code < 58); 40 | }; 41 | 42 | const getTokenType = function getTokenType(code: number): DateTokenType { 43 | // if (isWhitespace(code)) { 44 | // return DateTokenType.whitespace; 45 | // } 46 | 47 | // if (isDelimiter(code)) { 48 | // return DateTokenType.delimiter; 49 | // } 50 | 51 | if (isWhitespace(code) || isDelimiter(code)) { 52 | return DateTokenType.delimiter; 53 | } 54 | 55 | if (isNumericCode(code)) { 56 | return DateTokenType.numeric; 57 | } 58 | 59 | // if (isAlphaCode(code)) { 60 | return DateTokenType.alphanumeric; 61 | // } 62 | 63 | // return DateTokenType.unknown; 64 | }; 65 | 66 | const getNextTokenType = function getNextTokenType( 67 | currentTokenType: DateTokenType, 68 | nextCode: number, 69 | ): [DateTokenType, DateTokenType | null] { 70 | const nextTokenType = getTokenType(nextCode); 71 | 72 | if (currentTokenType === DateTokenType.initial) { 73 | return [nextTokenType, nextTokenType]; 74 | } 75 | 76 | if ( 77 | currentTokenType === DateTokenType.alphanumeric && 78 | nextTokenType === DateTokenType.numeric 79 | ) { 80 | return [DateTokenType.alphanumeric, null]; 81 | } 82 | 83 | if ( 84 | currentTokenType === DateTokenType.numeric && 85 | nextTokenType === DateTokenType.alphanumeric 86 | ) { 87 | return [DateTokenType.alphanumeric, DateTokenType.alphanumeric]; 88 | } 89 | 90 | return [nextTokenType, null]; 91 | }; 92 | 93 | const tokenizeDate = function tokenizeDate(input: string): DateToken[] { 94 | const tokens: DateToken[] = []; 95 | 96 | let currentToken: DateToken = [DateTokenType.initial, ""]; 97 | 98 | for (let i = 0; i < input.length; i++) { 99 | const char = input[i]; 100 | const code = char.charCodeAt(0); 101 | 102 | const [nextTokenType, updatedTokenType] = getNextTokenType( 103 | currentToken[0], 104 | code, 105 | ); 106 | 107 | if (updatedTokenType !== null) { 108 | currentToken[0] = updatedTokenType; 109 | } 110 | 111 | if (currentToken[0] !== nextTokenType) { 112 | if (currentToken[1].length > 0) { 113 | tokens.push(currentToken); 114 | } 115 | 116 | currentToken = [nextTokenType, char]; 117 | 118 | continue; 119 | } 120 | 121 | currentToken[1] += char; 122 | } 123 | 124 | if (currentToken[1].length > 0) { 125 | tokens.push(currentToken); 126 | } 127 | 128 | return tokens; 129 | }; 130 | 131 | export { type DateToken, DateTokenType, tokenizeDate }; 132 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and 9 | expression, level of experience, education, socio-economic status, nationality, 10 | personal appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or reject 41 | comments, commits, code, wiki edits, issues, and other contributions that are 42 | not aligned to this Code of Conduct, or to ban temporarily or permanently any 43 | contributor for other behaviors that they deem inappropriate, threatening, 44 | offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at eser@ozvataf.com. All complaints will 59 | be reviewed and investigated and will result in a response that is deemed 60 | necessary and appropriate to the circumstances. The project team is obligated to 61 | maintain confidentiality with regard to the reporter of an incident. Further 62 | details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 71 | version 1.4, available at 72 | https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 73 | 74 | [homepage]: https://www.contributor-covenant.org 75 | 76 | For answers to common questions about this code of conduct, see 77 | https://www.contributor-covenant.org/faq 78 | -------------------------------------------------------------------------------- /src/locales/generic-europe-asia.ts: -------------------------------------------------------------------------------- 1 | import { type Locale } from "./types.ts"; 2 | import { combineMonthNames, combineWeekdayNames } from "./combiners.ts"; 3 | import { locale as enGB } from "./en-GB.ts"; 4 | import { locale as deDE } from "./de-DE.ts"; 5 | import { locale as frFR } from "./fr-FR.ts"; 6 | import { locale as itIT } from "./it-IT.ts"; 7 | import { locale as esES } from "./es-ES.ts"; 8 | import { locale as trTR } from "./tr-TR.ts"; 9 | 10 | let i = 0; 11 | 12 | const locale: Locale = { 13 | code: "generic-europe-asia", 14 | 15 | isDayPlacedFirst: true, 16 | dateDelimiters: ["/", ".", "-"], 17 | 18 | dateFormats: { 19 | full: "EEEE, d MMMM yyyy", 20 | wide: "d MMMM yyyy", 21 | long: "d MMM yyyy", 22 | short: "dd/MM/yyyy", 23 | 24 | [++i]: "yyyy/M/d", 25 | [++i]: "d/M/yyyy", 26 | [++i]: "M/yyyy", 27 | [++i]: "yyyy/M", 28 | // ---- 29 | [++i]: "yyyy-M-d", 30 | [++i]: "d-M-yyyy", 31 | [++i]: "d-MMM-yyyy", 32 | [++i]: "d-MMMM-yyyy", 33 | [++i]: "M-yyyy", 34 | [++i]: "yyyy-M", 35 | // ---- 36 | [++i]: "yyyy.M.dd", 37 | [++i]: "d.M.yyyy", 38 | [++i]: "d.MMM.yyyy", 39 | [++i]: "d.MMMM.yyyy", 40 | [++i]: "M.yyyy", 41 | [++i]: "yyyy.M", 42 | // ---- 43 | [++i]: "yyyy M d", 44 | [++i]: "d M yyyy", 45 | [++i]: "d MMM yyyy", 46 | [++i]: "d MMMM yyyy", 47 | [++i]: "M yyyy", 48 | [++i]: "yyyy M", 49 | // ---- 50 | [++i]: "d, M, yyyy", 51 | [++i]: "d, MMM, yyyy", 52 | [++i]: "d, MMMM, yyyy", 53 | // ---- 54 | [++i]: "MMM d", 55 | [++i]: "MMMM d", 56 | // ---- 57 | [++i]: "d MMM", 58 | [++i]: "d MMMM", 59 | // ---- 60 | [++i]: "d-MMM", 61 | [++i]: "d-MMMM", 62 | // ---- 63 | [++i]: "MMM yyyy", 64 | [++i]: "MMMM yyyy", 65 | // ---- 66 | [++i]: "yyyy MMM d", 67 | [++i]: "yyyy MMMM d", 68 | // ---- 69 | [++i]: "d/M", 70 | [++i]: "MMM-d", 71 | [++i]: "MMMM, d", 72 | [++i]: "MMMM d, yyyy", 73 | [++i]: "MMMM, yyyy", 74 | // ---- 75 | [++i]: "qq yyyy", 76 | [++i]: "yyyy qq", 77 | [++i]: "EE, d MMMM yyyy", 78 | // ---- extended: will be removed in the future 79 | [++i]: "dd/MMMM/yyyy", 80 | [++i]: "dd/MMM/yyyy", 81 | [++i]: "d/MMMM/yyyy", 82 | [++i]: "d/MMM/yyyy", 83 | [++i]: "MMMM dd yyyy", 84 | [++i]: "MMMM d yyyy", 85 | [++i]: "MMMM/dd/yyyy", 86 | [++i]: "MMMM/d/yyyy", 87 | [++i]: "MMMM.dd.yyyy", 88 | [++i]: "MMMM.d.yyyy", 89 | [++i]: "MMMM-dd-yyyy", 90 | [++i]: "MMMM-d-yyyy", 91 | [++i]: "MMMM.yyyy", 92 | [++i]: "MMMM-yyyy", 93 | [++i]: "MMM/yyyy", 94 | [++i]: "MMM.yyyy", 95 | [++i]: "MMM-yyyy", 96 | [++i]: "MMM/yy", 97 | [++i]: "MMM.yy", 98 | [++i]: "yyyy MMM", 99 | [++i]: "yyyy/MMM", 100 | [++i]: "yyyy.MMM", 101 | [++i]: "yyyy-MMM", 102 | [++i]: "dd/MMM", 103 | [++i]: "dd.MMM", 104 | [++i]: "qq/yyyy", 105 | [++i]: "qq.yyyy", 106 | [++i]: "qq-yyyy", 107 | }, 108 | timeFormats: { 109 | full: "HH:mm:ss zzzz", 110 | wide: "HH:mm:ss z", 111 | long: "HH:mm:ss", 112 | short: "HH:mm", 113 | }, 114 | dateTimeFormats: { 115 | full: "{{date}} {{time}}", 116 | wide: "{{date}} {{time}}", 117 | long: "{{date}} {{time}}", 118 | short: "{{date}} {{time}}", 119 | }, 120 | 121 | monthNames: { 122 | full: combineMonthNames("full", enGB, deDE, frFR, itIT, esES, trTR), 123 | short: combineMonthNames("short", enGB, deDE, frFR, itIT, esES, trTR), 124 | }, 125 | dayNames: { 126 | full: combineWeekdayNames("full", enGB, deDE, frFR, itIT, esES, trTR), 127 | short: combineWeekdayNames("short", enGB, deDE, frFR, itIT, esES, trTR), 128 | }, 129 | }; 130 | 131 | export { locale }; 132 | -------------------------------------------------------------------------------- /src/parser.ts: -------------------------------------------------------------------------------- 1 | import { type DateFormat } from "./types.ts"; 2 | import { type Locale, locales, type SupportedLocales } from "./locales.ts"; 3 | import { 4 | type DateToken, 5 | DateTokenType, 6 | tokenizeDate, 7 | } from "./date-tokenizer.ts"; 8 | import { 9 | type FormatSymbol, 10 | FormatToken, 11 | FormatTokenType, 12 | quarters, 13 | symbols, 14 | tokenizeFormat, 15 | } from "./format-tokenizer.ts"; 16 | 17 | const ensureFitsToConstraints = function ensureFitsToConstraints( 18 | formatToken: FormatToken, 19 | dateToken: DateToken, 20 | ): boolean { 21 | if (formatToken[0] === FormatTokenType.literal) { 22 | if (formatToken[1] !== dateToken[1]) { 23 | return false; 24 | } 25 | } 26 | 27 | if (formatToken[0] === FormatTokenType.placeholder) { 28 | const symbol = symbols[formatToken[1]]; 29 | 30 | const length = dateToken[1].length; 31 | 32 | if (length < symbol.options.minLength) { 33 | return false; 34 | } 35 | 36 | if ( 37 | symbol.options.maxLength !== null && length > symbol.options.maxLength 38 | ) { 39 | return false; 40 | } 41 | 42 | if ( 43 | symbol.options.type === "numeric" && 44 | dateToken[0] !== DateTokenType.numeric 45 | ) { 46 | return false; 47 | } 48 | 49 | if ( 50 | symbol.options.type === "alphanumeric" && 51 | dateToken[0] !== DateTokenType.alphanumeric 52 | ) { 53 | return false; 54 | } 55 | } 56 | 57 | return true; 58 | }; 59 | 60 | const findLookupValueIfAny = function findLookupValueIfAny( 61 | symbol: FormatSymbol, 62 | dateToken: DateToken, 63 | locale: Locale, 64 | ): string | undefined { 65 | if (symbol.key === "month" && symbol.options.type === "alphanumeric") { 66 | if ( 67 | symbol.options.display === "short" || symbol.options.display === "full" 68 | ) { 69 | const findResult = Object.entries( 70 | locale.monthNames[symbol.options.display], 71 | ).find(( 72 | [, value], 73 | ) => value.includes(dateToken[1])); 74 | 75 | return findResult?.[0]; 76 | } 77 | 78 | return undefined; 79 | } 80 | 81 | if (symbol.key === "weekday" && symbol.options.type === "alphanumeric") { 82 | if ( 83 | symbol.options.display === "short" || symbol.options.display === "full" 84 | ) { 85 | const findResult = Object.entries(locale.dayNames[symbol.options.display]) 86 | .find(( 87 | [, value], 88 | ) => value.includes(dateToken[1])); 89 | 90 | if (findResult === undefined) { 91 | return undefined; 92 | } 93 | 94 | return String(Number(findResult[0]) + 1); 95 | } 96 | 97 | return undefined; 98 | } 99 | 100 | if (symbol.key === "quarter" && symbol.options.type === "alphanumeric") { 101 | return String(quarters.findIndex((name) => name === dateToken[1])); 102 | } 103 | 104 | return undefined; 105 | }; 106 | 107 | const tryParseDateWithFormat = function tryParseDateWithFormat( 108 | dateTokens: DateToken[], 109 | dateFormat: string, 110 | locale: Locale, 111 | ): DateFormat | undefined { 112 | const formatTokens = tokenizeFormat(dateFormat); 113 | 114 | // console.log(dateFormat, formatTokenizerToRegExp(formatTokens)); 115 | if (formatTokens.length !== dateTokens.length) { 116 | return undefined; 117 | } 118 | 119 | const result: Record = {}; 120 | 121 | for (let i = 0; i < formatTokens.length; i++) { 122 | const formatToken = formatTokens[i]; 123 | const dateToken = dateTokens[i]; 124 | 125 | if (!ensureFitsToConstraints(formatToken, dateToken)) { 126 | return undefined; 127 | } 128 | 129 | if (formatToken[0] === FormatTokenType.placeholder) { 130 | const symbol = symbols[formatToken[1]]; 131 | 132 | const value = findLookupValueIfAny(symbol, dateToken, locale); 133 | 134 | if (value !== undefined) { 135 | result[symbol.key] = value; 136 | } else { 137 | result[symbol.key] = dateToken[1]; 138 | } 139 | 140 | // console.log( 141 | // dateFormat, 142 | // `symbol: ${formatToken[1]}, name: ${symbol.name}, value: ${ 143 | // result[symbol.key] 144 | // }, maxLength: ${symbol.options.maxLength}`, 145 | // ); 146 | } 147 | } 148 | 149 | // console.log(dateFormat, result); 150 | 151 | return result; 152 | }; 153 | 154 | const parseDate = function parseDate( 155 | input: string, 156 | targetLocale: SupportedLocales | Locale, 157 | ): DateFormat | undefined { 158 | const tokens = tokenizeDate(input); 159 | const locale = (targetLocale.constructor === String) 160 | ? locales[targetLocale] 161 | : targetLocale; 162 | 163 | for (const [, dateFormat] of Object.entries(locale.dateFormats)) { 164 | const date = tryParseDateWithFormat(tokens, dateFormat, locale); 165 | 166 | if (date !== undefined) { 167 | return date; 168 | } 169 | } 170 | 171 | return undefined; 172 | }; 173 | 174 | export { parseDate }; 175 | -------------------------------------------------------------------------------- /src/sample-dates.ts: -------------------------------------------------------------------------------- 1 | const dateSamplesEA = [ 2 | "01 2022", 3 | "29 01 2022", 4 | "01-2022", 5 | "29-01-2022", 6 | "29, 01, 2022", 7 | "01.2022", 8 | "29.01.2022", 9 | "01/02/2022", 10 | "01/2022", 11 | "29/01/2022", 12 | "05/08/1930", 13 | "08-05-1930", 14 | // "08-05-30", // ! unhandled 15 | // "08-05", // ! unhandled 16 | "Oca 22", 17 | "Oca 2022", 18 | "Şubat 2025", 19 | "1/1/2022", 20 | "1930-08-05", 21 | "2019 Ocak 1", 22 | "2022 01", 23 | "2022-01-11", 24 | "2022-01", 25 | "2022.01", 26 | "2022/01", 27 | "2022/01/01", 28 | "29 01 2022", 29 | "29 Ocak", 30 | "29 Oca", 31 | "29-01-2022", 32 | "29, 01, 2022", 33 | "29.01.2022", 34 | // "29/01/022", // ! unhandled 35 | "5 Ağu 1930", 36 | "5 Ağustos 1930", 37 | "5-Eyl-1930", 38 | "5-Ağu", 39 | "5/8", 40 | "5/8/1930", 41 | // "5/8/30", // ! unhandled 42 | "Ağu-5", 43 | "Ağustos 2019", 44 | "Ağustos 5, 1930", 45 | "Ağustos 5", 46 | "Ocak 2022", 47 | "Ocak, 2022", 48 | "Temmuz 1, 2019", 49 | "Q2 2021", 50 | "Salı, 5 Ağustos 1930", 51 | 52 | // will be removed in the future 53 | "01 August 2022", 54 | "01/August/2022", 55 | "01.August.2022", 56 | "01-August-2022", 57 | "1 August 2022", 58 | "1/August/2022", 59 | "1.August.2022", 60 | "1-August-2022", 61 | "August 01 2022", 62 | "August/01/2022", 63 | "August.01.2022", 64 | "August-01-2022", 65 | "August 1 2022", 66 | "August/1/2022", 67 | "August.1.2022", 68 | "August-1-2022", 69 | "08 2022", 70 | "08/2022", 71 | "08.2022", 72 | "08-2022", 73 | "August 2022", 74 | "August.2022", 75 | "August-2022", 76 | "Aug 2022", 77 | "Aug/2022", 78 | "Aug.2022", 79 | "Aug-2022", 80 | "Aug 22", 81 | "Aug/22", 82 | "Aug.22", 83 | "Aug-22", 84 | "Aug 22", 85 | "Aug/22", 86 | "Aug.22", 87 | "Aug-22", 88 | "2022 Aug", 89 | "2022/Aug", 90 | "2022.Aug", 91 | "2022-Aug", 92 | "22 Aug", 93 | "22/Aug", 94 | "22.Aug", 95 | "22-Aug", 96 | "Q1 2022", 97 | "Q1/2022", 98 | "Q1.2022", 99 | "Q1-2022", 100 | ]; 101 | 102 | const dateSamplesUS = [ 103 | "01 2022", 104 | "01 29 2022", 105 | "01-2022", 106 | "01-29-2022", 107 | "01, 29, 2022", 108 | "01.2022", 109 | "01.29.2022", 110 | "02/01/2022", 111 | "01/2022", 112 | "01/29/2022", 113 | "08/05/1930", 114 | "05-08-1930", 115 | // "05-08-30", // ! unhandled 116 | // "05-08", // ! unhandled 117 | "Jan 22", 118 | "Jan 2022", 119 | "February 2025", 120 | "1/1/2022", 121 | "1930-08-05", 122 | "2019 January 1", 123 | "2022 01", 124 | "2022-01-11", 125 | "2022-01", 126 | "2022.01", 127 | "2022/01", 128 | "2022/01/01", 129 | "01 29 2022", 130 | "29 January", 131 | "29 Jan", 132 | "01-29-2022", 133 | "01, 29, 2022", 134 | "01.29.2022", 135 | // "01/29/022", // ! unhandled 136 | "5 Aug 1930", 137 | "5 August 1930", 138 | "5-Sep-1930", 139 | "5-Aug", 140 | "8/5", 141 | "8/5/1930", 142 | // "8/5/30", // ! unhandled 143 | "Aug-5", 144 | "August 2019", 145 | "August 5, 1930", 146 | "August 5", 147 | "January 2022", 148 | "January, 2022", 149 | "July 1, 2019", 150 | "Q2 2021", 151 | "Tuesday, 5 August 1930", 152 | 153 | // will be removed in the future 154 | "01 August 2022", 155 | "01/August/2022", 156 | "01.August.2022", 157 | "01-August-2022", 158 | "1 August 2022", 159 | "1/August/2022", 160 | "1.August.2022", 161 | "1-August-2022", 162 | "August 01 2022", 163 | "August/01/2022", 164 | "August.01.2022", 165 | "August-01-2022", 166 | "August 1 2022", 167 | "August/1/2022", 168 | "August.1.2022", 169 | "August-1-2022", 170 | "08 2022", 171 | "08/2022", 172 | "08.2022", 173 | "08-2022", 174 | "August 2022", 175 | "August.2022", 176 | "August-2022", 177 | "Aug 2022", 178 | "Aug/2022", 179 | "Aug.2022", 180 | "Aug-2022", 181 | "Aug 22", 182 | "Aug/22", 183 | "Aug.22", 184 | "Aug-22", 185 | "Aug 22", 186 | "Aug/22", 187 | "Aug.22", 188 | "Aug-22", 189 | "2022 Aug", 190 | "2022/Aug", 191 | "2022.Aug", 192 | "2022-Aug", 193 | "22 Aug", 194 | "22/Aug", 195 | "22.Aug", 196 | "22-Aug", 197 | "Q1 2022", 198 | "Q1/2022", 199 | "Q1.2022", 200 | "Q1-2022", 201 | ]; 202 | 203 | const timeSamplesEA = [ 204 | "1:25 PM", 205 | "12:00 AM", 206 | "1:25:59 PM", 207 | "1:25:59 AM", 208 | "13:25:59", 209 | "00:25:59", 210 | "13:25", 211 | "00:00", 212 | ]; 213 | 214 | const timeSamplesUS = [ 215 | "1:25 PM", 216 | "12:00 AM", 217 | "1:25:59 PM", 218 | "1:25:59 AM", 219 | "13:25:59", 220 | "00:25:59", 221 | "13:25", 222 | "00:00", 223 | ]; 224 | 225 | const dateTimeSamplesEA = [ 226 | ...dateSamplesEA, 227 | ...timeSamplesEA, 228 | "Tuesday, 5 August 1930 at 13:25:59", 229 | "Tuesday, 5 August 1930, 13:25:59", 230 | ]; 231 | 232 | const dateTimeSamplesUS = [ 233 | ...dateSamplesUS, 234 | ...timeSamplesUS, 235 | "Tuesday, 5 August 1930 at 13:25:59", 236 | "Tuesday, 5 August 1930, 13:25:59", 237 | ]; 238 | 239 | export { 240 | dateSamplesEA, 241 | dateSamplesUS, 242 | dateTimeSamplesEA, 243 | dateTimeSamplesUS, 244 | timeSamplesEA, 245 | timeSamplesUS, 246 | }; 247 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Eser Ozvataf 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/format-tokenizer.ts: -------------------------------------------------------------------------------- 1 | interface FormatSymbol { 2 | key: string; 3 | name: string; 4 | options: { 5 | type: "numeric" | "alphanumeric"; 6 | display: 7 | | "numeric" 8 | | "2-digit" 9 | | "narrow" 10 | | "short" 11 | | "long" 12 | | "wide" 13 | | "full"; 14 | hour12?: boolean; 15 | minLength: number; 16 | maxLength: number | null; 17 | minValue?: number; 18 | maxValue?: number; 19 | }; 20 | } 21 | 22 | const quarters = ["Q1", "Q2", "Q3", "Q4"]; 23 | 24 | // ref: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table 25 | const symbols: Record = { 26 | // "G": "era", // ! not supported 27 | // "Y": "year", // ! not supported 28 | "yyyy": { 29 | key: "year", 30 | name: "year", 31 | options: { 32 | type: "numeric", 33 | display: "numeric", 34 | minLength: 4, 35 | maxLength: 4, 36 | minValue: 0, 37 | maxValue: 9999, 38 | }, 39 | }, 40 | "yyy": { 41 | key: "year", 42 | name: "year", 43 | options: { 44 | type: "numeric", 45 | display: "numeric", 46 | minLength: 3, 47 | maxLength: 3, 48 | minValue: 0, 49 | maxValue: 999, 50 | }, 51 | }, 52 | "yy": { 53 | key: "year", 54 | name: "year", 55 | options: { 56 | type: "numeric", 57 | display: "2-digit", 58 | minLength: 2, 59 | maxLength: 2, 60 | minValue: 0, 61 | maxValue: 99, 62 | }, 63 | }, 64 | // "u": "extended year", // ! not supported 65 | // "U": "cyclic year", // ! not supported 66 | // "r": "related gregorian year", // ! not supported 67 | // "Q": { key: "quarter", name: "quarter" }, // ! not supported 68 | "qq": { 69 | key: "quarter", 70 | name: "quarter", 71 | options: { 72 | type: "alphanumeric", 73 | display: "narrow", 74 | minLength: 2, 75 | maxLength: 2, 76 | minValue: 1, 77 | maxValue: 4, 78 | }, 79 | }, 80 | "q": { 81 | key: "quarter", 82 | name: "quarter", 83 | options: { 84 | type: "numeric", 85 | display: "numeric", 86 | minLength: 1, 87 | maxLength: 1, 88 | minValue: 1, 89 | maxValue: 4, 90 | }, 91 | }, 92 | "MMMM": { 93 | key: "month", 94 | name: "month", 95 | options: { 96 | type: "alphanumeric", 97 | display: "full", 98 | minLength: 3, 99 | maxLength: null, 100 | minValue: 1, 101 | maxValue: 12, 102 | }, 103 | }, 104 | "MMM": { 105 | key: "month", 106 | name: "month", 107 | options: { 108 | type: "alphanumeric", 109 | display: "short", 110 | minLength: 3, 111 | maxLength: 3, 112 | minValue: 1, 113 | maxValue: 12, 114 | }, 115 | }, 116 | "MM": { 117 | key: "month", 118 | name: "month", 119 | options: { 120 | type: "numeric", 121 | display: "2-digit", 122 | minLength: 2, 123 | maxLength: 2, 124 | minValue: 1, 125 | maxValue: 12, 126 | }, 127 | }, 128 | "M": { 129 | key: "month", 130 | name: "month", 131 | options: { 132 | type: "numeric", 133 | display: "numeric", 134 | minLength: 1, 135 | maxLength: 2, 136 | minValue: 1, 137 | maxValue: 12, 138 | }, 139 | }, 140 | // "L": { key: "month", name: "month" }, // ! not supported 141 | // "I": "nothing (deprecated)", // ! not supported 142 | // "w": "week of year", // ! not supported 143 | // "W": "week of month", // ! not supported 144 | "dd": { 145 | key: "day", 146 | name: "day of month", 147 | options: { 148 | type: "numeric", 149 | display: "2-digit", 150 | minLength: 2, 151 | maxLength: 2, 152 | minValue: 1, 153 | maxValue: 31, 154 | }, 155 | }, 156 | "do": { // 1st, 2nd, 3rd, 4th, etc. 157 | key: "day", 158 | name: "day of month", 159 | options: { 160 | type: "numeric", 161 | display: "2-digit", 162 | minLength: 2, 163 | maxLength: 2, 164 | minValue: 1, 165 | maxValue: 31, 166 | }, 167 | }, 168 | "d": { 169 | key: "day", 170 | name: "day of month", 171 | options: { 172 | type: "numeric", 173 | display: "numeric", 174 | minLength: 1, 175 | maxLength: 2, 176 | minValue: 1, 177 | maxValue: 31, 178 | }, 179 | }, 180 | // "D": "day of year", // ! not supported 181 | // "F": "day of week in month", // ! not supported 182 | // "g": "modified julian day", // ! not supported 183 | "EE": { 184 | key: "weekday", 185 | name: "weekday name", 186 | options: { 187 | type: "alphanumeric", 188 | display: "full", 189 | minLength: 3, 190 | maxLength: null, 191 | minValue: 1, 192 | maxValue: 7, 193 | }, 194 | }, 195 | "E": { 196 | key: "weekday", 197 | name: "weekday name", 198 | options: { 199 | type: "alphanumeric", 200 | display: "short", 201 | minLength: 2, 202 | maxLength: 3, 203 | minValue: 1, 204 | maxValue: 7, 205 | }, 206 | }, 207 | "ee": { 208 | key: "weekday", 209 | name: "weekday", 210 | options: { 211 | type: "numeric", 212 | display: "2-digit", 213 | minLength: 2, 214 | maxLength: 2, 215 | minValue: 1, 216 | maxValue: 7, 217 | }, 218 | }, 219 | "e": { 220 | key: "weekday", 221 | name: "weekday", 222 | options: { 223 | type: "numeric", 224 | display: "numeric", 225 | minLength: 1, 226 | maxLength: 2, 227 | minValue: 1, 228 | maxValue: 7, 229 | }, 230 | }, 231 | // "c": "weekday", // ! not supported 232 | "aa": { 233 | key: "dayPeriod", 234 | name: "day period", 235 | options: { 236 | type: "alphanumeric", 237 | display: "short", 238 | minLength: 2, 239 | maxLength: 2, 240 | minValue: 1, 241 | maxValue: 2, 242 | }, 243 | }, 244 | "a": { 245 | key: "dayPeriod", 246 | name: "day period", 247 | options: { 248 | type: "alphanumeric", 249 | display: "narrow", 250 | minLength: 1, 251 | maxLength: 1, 252 | minValue: 1, 253 | maxValue: 2, 254 | }, 255 | }, 256 | // "b": "extended day period", // ! not supported 257 | // "B": "flexible day period", // ! not supported 258 | "hh": { 259 | key: "hour", 260 | name: "hour 1-12", 261 | options: { 262 | type: "numeric", 263 | display: "2-digit", 264 | hour12: true, 265 | minLength: 2, 266 | maxLength: 2, 267 | minValue: 1, 268 | maxValue: 12, 269 | }, 270 | }, 271 | "h": { 272 | key: "hour", 273 | name: "hour 1-12", 274 | options: { 275 | type: "numeric", 276 | display: "numeric", 277 | hour12: true, 278 | minLength: 1, 279 | maxLength: 2, 280 | minValue: 1, 281 | maxValue: 12, 282 | }, 283 | }, 284 | "HH": { 285 | key: "hour", 286 | name: "hour 0-23", 287 | options: { 288 | type: "numeric", 289 | display: "2-digit", 290 | hour12: false, 291 | minLength: 2, 292 | maxLength: 2, 293 | minValue: 0, 294 | maxValue: 23, 295 | }, 296 | }, 297 | "H": { 298 | key: "hour", 299 | name: "hour 0-23", 300 | options: { 301 | type: "numeric", 302 | display: "numeric", 303 | hour12: false, 304 | minLength: 1, 305 | maxLength: 2, 306 | minValue: 0, 307 | maxValue: 23, 308 | }, 309 | }, 310 | // "K": "hour 0-11", // ! not supported 311 | // "k": "hour 1-24", // ! not supported 312 | // "j": "hour", // ! not supported 313 | // "J": "hour", // ! not supported 314 | // "C": "hour", // ! not supported 315 | "mm": { 316 | key: "minute", 317 | name: "minute", 318 | options: { 319 | type: "numeric", 320 | display: "2-digit", 321 | minLength: 2, 322 | maxLength: 2, 323 | minValue: 0, 324 | maxValue: 59, 325 | }, 326 | }, 327 | "m": { 328 | key: "minute", 329 | name: "minute", 330 | options: { 331 | type: "numeric", 332 | display: "numeric", 333 | minLength: 1, 334 | maxLength: 2, 335 | minValue: 0, 336 | maxValue: 59, 337 | }, 338 | }, 339 | "ss": { 340 | key: "second", 341 | name: "second", 342 | options: { 343 | type: "numeric", 344 | display: "2-digit", 345 | minLength: 2, 346 | maxLength: 2, 347 | minValue: 0, 348 | maxValue: 59, 349 | }, 350 | }, 351 | "s": { 352 | key: "second", 353 | name: "second", 354 | options: { 355 | type: "numeric", 356 | display: "numeric", 357 | minLength: 1, 358 | maxLength: 2, 359 | minValue: 0, 360 | maxValue: 59, 361 | }, 362 | }, 363 | // "S": "fractional second", // ! not supported 364 | // "A": "millisecond in day", // ! not supported 365 | "zz": { 366 | key: "timezone", 367 | name: "timezone", 368 | options: { 369 | type: "alphanumeric", 370 | display: "full", 371 | minLength: 3, 372 | maxLength: null, 373 | }, 374 | }, 375 | "z": { 376 | key: "timezone", 377 | name: "timezone", 378 | options: { 379 | type: "alphanumeric", 380 | display: "short", 381 | minLength: 3, 382 | maxLength: 3, 383 | }, 384 | }, 385 | // "Z": "timezone", // ! not supported 386 | // "O": "timezone", // ! not supported 387 | // "v": "timezone", // ! not supported 388 | // "V": "timezone", // ! not supported 389 | // "X": "timezone", // ! not supported 390 | // "x": "timezone", // ! not supported 391 | }; 392 | 393 | const enum FormatTokenType { 394 | unknown = 0, 395 | literal = 1, 396 | placeholder = 2, 397 | } 398 | 399 | interface FormatToken { 400 | length: 2; 401 | 0: FormatTokenType; 402 | 1: string; 403 | } 404 | 405 | const tokenizeFormat = function tokenizeFormat(input: string): FormatToken[] { 406 | const tokens: FormatToken[] = []; 407 | 408 | let currentToken: FormatToken = [FormatTokenType.unknown, ""]; 409 | 410 | const pushToken = function pushToken() { 411 | let tokenType = currentToken[0] ?? FormatTokenType.unknown; 412 | 413 | if (tokenType === FormatTokenType.unknown) { 414 | if (currentToken[1] in symbols) { 415 | tokenType = FormatTokenType.placeholder; 416 | } else { 417 | tokenType = FormatTokenType.literal; 418 | } 419 | } 420 | 421 | // console.log(currentToken, tokens.at(-1)); 422 | if ( 423 | tokenType === FormatTokenType.literal && 424 | tokens.slice(-1)?.[0]?.[0] === FormatTokenType.literal 425 | ) { 426 | tokens[tokens.length - 1][1] += currentToken[1]; 427 | 428 | return; 429 | } 430 | 431 | tokens.push([tokenType, currentToken[1]]); 432 | }; 433 | 434 | let inQuote = undefined; 435 | 436 | for (let i = 0; i < input.length; i++) { 437 | const char = input[i]; 438 | 439 | if (inQuote === undefined && currentToken[1].slice(-1) !== char) { 440 | if (currentToken[1].length > 0) { 441 | pushToken(); 442 | } 443 | 444 | currentToken = [FormatTokenType.unknown, ""]; 445 | } 446 | 447 | if (char === '"' || char === "'") { 448 | if (inQuote === undefined) { 449 | if (currentToken[0] === FormatTokenType.placeholder) { 450 | pushToken(); 451 | 452 | currentToken[1] = ""; 453 | } 454 | 455 | currentToken[0] = FormatTokenType.literal; 456 | inQuote = char; 457 | continue; 458 | } else if (inQuote === char) { 459 | inQuote = undefined; 460 | continue; 461 | } 462 | } 463 | 464 | currentToken[1] += char; 465 | } 466 | 467 | if (currentToken[1].length > 0) { 468 | pushToken(); 469 | } 470 | 471 | return tokens; 472 | }; 473 | 474 | const escapeRegExp = function escapeRegex(input: string) { 475 | // $& means the whole matched string 476 | return input.replace(/[.*+?^${}()|[\]\\\/]/g, "\\$&"); 477 | }; 478 | 479 | const formatTokenizerToRegExp = function formatTokenizerToRegExp( 480 | tokens: FormatToken[], 481 | ) { 482 | const regExp = tokens.reduce((acc, curr, idx, arr) => { 483 | if (curr[0] === FormatTokenType.literal) { 484 | return `${acc}${escapeRegExp(curr[1])}`; 485 | } 486 | 487 | let nextChar = "$"; 488 | const peek = arr[idx + 1]; 489 | if (peek !== undefined && peek[0] === FormatTokenType.literal) { 490 | nextChar = escapeRegExp(peek[1][0]!); 491 | } 492 | 493 | const symbol = symbols[curr[1]]; 494 | 495 | let chars; 496 | let length; 497 | if (symbol.options.display === "2-digit") { 498 | chars = "\\d"; 499 | length = "{2}"; 500 | } else if (symbol.options.display === "numeric") { 501 | chars = "\\d"; 502 | length = "+"; 503 | } else { 504 | chars = `^${nextChar}`; 505 | length = "+"; 506 | } 507 | 508 | return `${acc}(?<${symbol.key}>[${chars}]${length})`; 509 | }, ""); 510 | 511 | return regExp; 512 | }; 513 | 514 | export { 515 | type FormatSymbol, 516 | type FormatToken, 517 | formatTokenizerToRegExp, 518 | FormatTokenType, 519 | quarters, 520 | symbols, 521 | tokenizeFormat, 522 | }; 523 | --------------------------------------------------------------------------------