|
| 1 | +// obsidian already uses moment, so no need to package it twice! |
| 2 | +// import { moment } from 'obsidian'; // doesn't work for release build |
| 3 | +// obsidian uses a namespace-style import for moment, which ES6 doesn't allow anymore |
| 4 | +const obsidian = require('obsidian'); |
| 5 | +const moment = obsidian.moment; |
| 6 | + |
| 7 | +export class DateFormatter { |
| 8 | + toFormat: string; |
| 9 | + localeString: string; |
| 10 | + |
| 11 | + constructor() { |
| 12 | + this.toFormat = 'YYYY-MM-DD'; |
| 13 | + // get locale string (e.g. en, en-gb, de, fr, etc.) |
| 14 | + this.localeString = new Intl.DateTimeFormat().resolvedOptions().locale; |
| 15 | + } |
| 16 | + |
| 17 | + setFormat(format: string): void { |
| 18 | + this.toFormat = format; |
| 19 | + } |
| 20 | + |
| 21 | + getPreview(format?: string): string { |
| 22 | + const today = moment(); |
| 23 | + today.locale(this.localeString); |
| 24 | + |
| 25 | + if (!format) { |
| 26 | + format = this.toFormat; |
| 27 | + } |
| 28 | + |
| 29 | + return today.format(format); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Tries to format a given date string with the currently set date format. |
| 34 | + * You can set a date format by calling `setFormat()`. |
| 35 | + * |
| 36 | + * @param dateString the date string to be formatted |
| 37 | + * @param dateFormat the current format of `dateString`. When this is `null` and the actual format of the |
| 38 | + * given date string is not `C2822` or `ISO` format, this function will try to guess the format by using the native `Date` module. |
| 39 | + * @returns formatted date string or null if `dateString` is not a valid date |
| 40 | + */ |
| 41 | + format(dateString: string, dateFormat?: string): string | null { |
| 42 | + if (!dateString) { |
| 43 | + return null; |
| 44 | + } |
| 45 | + |
| 46 | + let date: moment.Moment; |
| 47 | + |
| 48 | + if (!dateFormat) { |
| 49 | + // reading date formats other then C2822 or ISO with moment is deprecated |
| 50 | + if (this.hasMomentFormat(dateString)) { |
| 51 | + // expect C2822 or ISO format |
| 52 | + date = moment(dateString); |
| 53 | + } else { |
| 54 | + // try to read date string with native Date |
| 55 | + date = moment(new Date(dateString)); |
| 56 | + } |
| 57 | + date.locale(this.localeString); // set local locale definition for moment |
| 58 | + } else { |
| 59 | + date = moment(dateString, dateFormat, this.localeString); |
| 60 | + } |
| 61 | + |
| 62 | + // format date (if it is valid) |
| 63 | + return date.isValid() ? date.format(this.toFormat) : null; |
| 64 | + } |
| 65 | + |
| 66 | + private hasMomentFormat(dateString: string): boolean { |
| 67 | + const date = moment(dateString, true); // strict mode |
| 68 | + return date.isValid(); |
| 69 | + } |
| 70 | +} |
0 commit comments