最好使用ISO 8601格式的日期和时间。请看看为什么以及使用ISO-8601日期格式有哪些好处。https://www.iso.org/iso-8601-date-and-time-format.html
完整文章在这里 在Angular中实现ISO 8601日期时间格式
ISO 8601可被任何希望使用标准化呈现方式的人使用:
日期,
一天中的时间,
协调世界时(UTC),
日期和时间,
时间间隔,
循环时间间隔。
您可以使用此代码以您想要的方式使用该格式。我希望这可以帮助您。
export interface HashTable<T> {
[key: string]: T;
}
import { Injectable } from '@angular/core';
import { HashTable } from './hash-table';
type FormatFunc = (date: Date) => string;
@Injectable({
providedIn: 'root'
})
export class DateFormat {
formattingTokenFunc: HashTable<FormatFunc> = {};
private formattingTokens = /(HH?|HH?|hh?|mm?|ss?|MM?|dd?|yy?y?y?|.)/g;
constructor() {
const getYearFunc = (date: Date) => date.getFullYear().toString();
this.addFormatToken('y', 0, (date: Date) =>
(date.getFullYear() % 100).toString()
);
this.addFormatToken('yyy', 0, getYearFunc);
this.addFormatToken('yyyy', 0, getYearFunc);
this.addFormatToken('yy', 3, (date: Date) =>
(date.getFullYear() % 100).toString()
);
const getMonthFunc = (date: Date) => (date.getMonth() + 1).toString();
this.addFormatToken('M', 0, getMonthFunc);
this.addFormatToken('MM', 2, getMonthFunc);
const getDayFunc = (date: Date) => date.getDate().toString();
this.addFormatToken('d', 0, getDayFunc);
this.addFormatToken('dd', 2, getDayFunc);
const get12HrFunc = (date: Date) => (date.getHours() % 12).toString();
this.addFormatToken('hh', 2, get12HrFunc);
this.addFormatToken('h', 0, get12HrFunc);
const get24HrFunc = (date: Date) => date.getHours().toString();
this.addFormatToken('HH', 2, get24HrFunc);
this.addFormatToken('H', 0, get24HrFunc);
const getMinFunc = (date: Date) => date.getMinutes().toString();
this.addFormatToken('m', 0, getMinFunc);
this.addFormatToken('mm', 2, getMinFunc);
const getSecFunc = (date: Date) => date.getSeconds().toString();
this.addFormatToken('s', 0, getSecFunc);
this.addFormatToken('ss', 2, getSecFunc);
}
formatToISO8601Date(date: Date | string): string {
return this.format(date, 'yyyy-MM-dd');
}
format(date: Date | string, format: string): string {
const finalDate = date instanceof Date ? date : new Date(date);
const matches = format.match(this.formattingTokens);
let result = '';
matches.forEach(match => {
const formatFunc = this.formattingTokenFunc[match];
result += formatFunc ? formatFunc(finalDate) : match;
});
return result;
}
prefixZero(length: number, input: string): string {
return `${Math.pow(10, length)}${input}`.slice(-1 * length);
}
prefixZeroFunc(length: number, formatFunc: FormatFunc): FormatFunc {
return (c: Date) => this.prefixZero(length, formatFunc(c));
}
private addFormatToken(
token: string,
addZeroesLength: number,
formatFunc: FormatFunc
): void {
this.formattingTokenFunc[token] =
addZeroesLength > 0
? this.prefixZeroFunc(addZeroesLength, formatFunc)
: formatFunc;
}
}