是否有办法将Javascript数据格式化为dd-mm-yyyy?



目前我从剑道日期选择器中获得一个日期,如(1)Sun Feb 01 2021 00:00:00 GMT+0000 (GMT)。但是,我希望这个日期的格式为年月日/年/月/年,所以我做了下面的逻辑来反映我想要的日期。下面的实现,返回例如以下日期26-01/2021,但在一个字符串类型。我想拥有一个Date对象,但不是以上述日期[(1)]所述的方式,而是类似于26 01 2021 00:00:00 GMT的东西。

这可能吗?


public static formatDate(dt: Date): string {
const isValid = this.isValidDate(dt);
if (isValid) {
const formattedDate = dt.toLocaleDateString('en-GB', {
day: 'numeric', month: 'numeric', year: 'numeric'
}).replace(///g, '-');
return formattedDate;
}
return null;
}
public static isValidDate(date) {
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}

您可以使用Intl。DateTimeFormat用于根据特定的区域设置格式化日期。

这个问题提到了dd-mm-yyyydd/mm/yyyy格式,所以这里有两个片段可以帮助:

public static formatDate(dt: Date): string {
return new Intl.DateTimeFormat('en-GB').format(dt); // returns the date in dd/mm/yyyy format
}
public static formatDate(dt: Date): string {
return new Intl.DateTimeFormat('en-GB').format(dt).replace(///g, '-'); // returns the date in dd-mm-yyyy format
}

最新更新