gpt4 book ai didi

angular-material - 使用 Material dayjs 日期适配器处理分隔符

转载 作者:行者123 更新时间:2023-12-03 20:45:51 31 4
gpt4 key购买 nike

在我的 Angular 应用程序中,我需要从 momentjs 进行交换至dayjs .
因为我用的是material我必须更换 moment-date-adapter使用 dayjs-date-adapter,所以我编写了自己的日期适配器,但我不明白 momentjs 如何解析像 12122020 这样的日期没有任何分隔符(您可以在操作中看到它 here )。
我尝试通过设置 MatDateFormats 来实现它,带有一个日期输入数组。
但我不知道这是否是最好的解决方案,因为我在 moment-date-adapter 中看不到它

MatDateFormats = {
parse: {
dateInput: ['D/M/YYYY', 'DMYYYY'],
},
display: {
dateInput: 'DD/MM/YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'DD/MM/YYYY',
monthYearA11yLabel: 'MMMM YYYY',
}
}
这是我的 dayjs-date-adapter
export interface DayJsDateAdapterOptions {
/**
* Turns the use of utc dates on or off.
* Changing this will change how Angular Material components like DatePicker output dates.
* {@default false}
*/
useUtc?: boolean;
}

/** InjectionToken for Dayjs date adapter to configure options. */
export const MAT_DAYJS_DATE_ADAPTER_OPTIONS = new InjectionToken<DayJsDateAdapterOptions>(
'MAT_DAYJS_DATE_ADAPTER_OPTIONS', {
providedIn: 'root',
factory: MAT_DAYJS_DATE_ADAPTER_OPTIONS_FACTORY
});

export function MAT_DAYJS_DATE_ADAPTER_OPTIONS_FACTORY(): DayJsDateAdapterOptions {
return {
useUtc: false
};
}

/** Creates an array and fills it with values. */
function range<T>(length: number, valueFunction: (index: number) => T): T[] {
const valuesArray = Array(length);
for (let i = 0; i < length; i++) {
valuesArray[i] = valueFunction(i);
}
return valuesArray;
}

/** Adapts Dayjs Dates for use with Angular Material. */
export class DayjsDateAdapter extends DateAdapter<Dayjs> {
private localeData: {
firstDayOfWeek: number,
longMonths: string[],
shortMonths: string[],
dates: string[],
longDaysOfWeek: string[],
shortDaysOfWeek: string[],
narrowDaysOfWeek: string[]
};

constructor(@Optional() @Inject(MAT_DATE_LOCALE) public dateLocale: string,
@Optional() @Inject(MAT_DAYJS_DATE_ADAPTER_OPTIONS) private options?:
DayJsDateAdapterOptions) {
super();

this.initializeParser(dateLocale);
}

private get shouldUseUtc(): boolean {
const {useUtc}: DayJsDateAdapterOptions = this.options || {};
return !!useUtc;
}

// TODO: Implement
setLocale(locale: string) {
super.setLocale(locale);

const dayJsLocaleData = this.dayJs().localeData();
this.localeData = {
firstDayOfWeek: dayJsLocaleData.firstDayOfWeek(),
longMonths: dayJsLocaleData.months(),
shortMonths: dayJsLocaleData.monthsShort(),
dates: range(31, (i) => this.createDate(2017, 0, i + 1).format('D')),
longDaysOfWeek: range(7, (i) => this.dayJs().set('day', i).format('dddd')),
shortDaysOfWeek: dayJsLocaleData.weekdaysShort(),
narrowDaysOfWeek: dayJsLocaleData.weekdaysMin(),
};
}

getYear(date: Dayjs): number {
return this.dayJs(date).year();
}

getMonth(date: Dayjs): number {
return this.dayJs(date).month();
}

getDate(date: Dayjs): number {
return this.dayJs(date).date();
}

getDayOfWeek(date: Dayjs): number {
return this.dayJs(date).day();
}

getMonthNames(style: 'long' | 'short' | 'narrow'): string[] {
return style === 'long' ? this.localeData.longMonths : this.localeData.shortMonths;
}

getDateNames(): string[] {
return this.localeData.dates;
}

getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] {
if (style === 'long') {
return this.localeData.longDaysOfWeek;
}
if (style === 'short') {
return this.localeData.shortDaysOfWeek;
}
return this.localeData.narrowDaysOfWeek;
}

getYearName(date: Dayjs): string {
return this.dayJs(date).format('YYYY');
}

getFirstDayOfWeek(): number {
return this.localeData.firstDayOfWeek;
}

getNumDaysInMonth(date: Dayjs): number {
return this.dayJs(date).daysInMonth();
}

clone(date: Dayjs): Dayjs {
return date.clone();
}

createDate(year: number, month: number, date: number): Dayjs {
const returnDayjs = this.dayJs()
.set('year', year)
.set('month', month)
.set('date', date);
return returnDayjs;
}

today(): Dayjs {
return this.dayJs();
}

parse(value: any, parseFormat: string): Dayjs | null {
if (value && typeof value === 'string') {
return this.dayJs(value, parseFormat, this.locale);
}
return value ? this.dayJs(value).locale(this.locale) : null;
}

format(date: Dayjs, displayFormat: string): string {
if (!this.isValid(date)) {
throw Error('DayjsDateAdapter: Cannot format invalid date.');
}
return date.locale(this.locale).format(displayFormat);
}

addCalendarYears(date: Dayjs, years: number): Dayjs {
return date.add(years, 'year');
}

addCalendarMonths(date: Dayjs, months: number): Dayjs {
return date.add(months, 'month');
}

addCalendarDays(date: Dayjs, days: number): Dayjs {
return date.add(days, 'day');
}

toIso8601(date: Dayjs): string {
return date.toISOString();
}


deserialize(value: any): Dayjs | null {
let date;
if (value instanceof Date) {
date = this.dayJs(value);
} else if (this.isDateInstance(value)) {
// NOTE: assumes that cloning also sets the correct locale.
return this.clone(value);
}
if (typeof value === 'string') {
if (!value) {
return null;
}
date = this.dayJs(value).toISOString();
}
if (date && this.isValid(date)) {
return this.dayJs(date);
}
return super.deserialize(value);
}

isDateInstance(obj: any): boolean {
return dayjs.isDayjs(obj);
}

isValid(date: Dayjs): boolean {
return this.dayJs(date).isValid();
}

invalid(): Dayjs {
return this.dayJs(null);
}

private dayJs(input?: any, format?: string, locale?: string): Dayjs {
if (!this.shouldUseUtc) {
return dayjs(input, format, locale, false);
}
return dayjs(input, {format, locale, utc: this.shouldUseUtc}, locale, false).utc();
}

private initializeParser(dateLocale: string) {
if (this.shouldUseUtc) {
dayjs.extend(utc);
}

dayjs.extend(LocalizedFormat);
dayjs.extend(customParseFormat);
dayjs.extend(localeData);

}
}

最佳答案

您在 MatDateFormats 的 parse 属性中使用的 dateInput 用于 dayjs-date-adapter 的 parse 函数。现在您提供一个数组作为 dateInput,但您的函数需要一个字符串。 Dayjs(与 moment 不同)无法处理格式数组。如果要使用数组来支持多种格式,则必须弄清楚要在解析函数中使用哪种格式的数组。最简单的方法可能只是遍历您可能的格式并返回 dayjs 对象(如果它是有效的)。
像这样的东西(注意我没有测试过这个):

parse(value: any, parseFormats: string[]): Dayjs | null {
if (value && typeof value === 'string') {
parseFormats.forEach(parseFormat => {
const parsed = this.dayJs(value, parseFormat, this.locale);
if (parsed.isValid()) {
return parsed;
}
}
// return an invalid object if it could not be parsed with the supplied formats
return this.dayJs(null);
}
return value ? this.dayJs(value).locale(this.locale) : null;
}
请注意,在我自己的适配器中,我稍微更改了私有(private) dayJs 函数,因为在格式选项中也提供语言环境给了我一些奇怪的行为。我不需要 utc 选项,所以我最终使用了:
private dayJs(input?: any, format?: string, locale?: string): Dayjs {
return dayjs(input, format, locale);
}

上述方法的替代方法是仅提供 1 个 dateInput(例如:dateInput: 'D/M/YYYY')。然后让 parse 函数更灵活一点。我最终得到了这个:
parse(value: any, parseFormat: string): Dayjs | null {
if (value && typeof value === 'string') {
const longDateFormat = dayjs().localeData().longDateFormat(parseFormat); // MM/DD/YYY or DD-MM-YYYY, etc.
// return this.dayJs(value, longDateFormat);
let parsed = this.dayJs(value, longDateFormat, this.locale);
if (parsed.isValid()) {
// string value is exactly like long date format
return parsed;
}
const alphaNumericRegex = /[\W_]+/;
if (!alphaNumericRegex.test(value)) {
// if string contains no non-word characters and no _
// user might have typed 24012020 or 01242020
// strip long date format of non-word characters and take only the length of the value so we get DDMMYYYY or DDMM etc
const format = longDateFormat.replace(/[\W_]+/g, '').substr(0, value.length);
parsed = this.dayJs(value, format, this.locale);
if (parsed.isValid()) {
return parsed;
}
}
const userDelimiter = alphaNumericRegex.exec(value) ? alphaNumericRegex.exec(value)![0] : '';
const localeDelimiter = alphaNumericRegex.exec(longDateFormat) ? alphaNumericRegex.exec(longDateFormat)![0] : '';
const parts = value.split(userDelimiter);
const formatParts = longDateFormat.split(localeDelimiter);
if (parts.length <= formatParts.length && parts.length < 4) {
// right now this only works for days, months, and years, if time should be supported this should be altered
let newFormat = '';
parts.forEach((part, index) => {
// get the format in the length of the part, so if a the date is supplied 1-1-19 this should result in D-M-YY
// note, this will not work if really weird input is supplied, but that's okay
newFormat += formatParts[index].substr(0, part.length);
if (index < parts.length - 1) {
newFormat += userDelimiter;
}
});
parsed = this.dayJs(value, newFormat);
if (parsed.isValid()) {
return parsed;
}
}

// not able to parse anything sensible, return something invalid so input can be corrected
return this.dayJs(null);
}

return value ? this.dayJs(value).locale(this.locale) : null;
}
如果您只想在指定输入旁边支持仅数字输入(如 28082021),则需要带有 !alphaNumericRegex.test(value) 的 if 语句。这段代码从您的格式化字符串中取出任何分隔符(如 - 或/),并确保支持仅包含天或天和月的字符串(例如 28 或 2808)。它将使用当前月份和年份来填充缺失值。如果您只想支持完整的日-月-年字符串,您可以省略 .substr 部分。
此 if 语句下方的代码导致支持不同类型的用户输入,例如 28-08-2021、28/08/2021、28 08 2021、28-08-21、28/08 等。
我确信它不适用于每种语言,但它适用于我的语言(荷兰语)中最常用的用户输入。
希望这也能帮助那些一直在努力解决这个问题的人!

关于angular-material - 使用 Material dayjs 日期适配器处理分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65687460/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com