Angular 如何检查日期是否为特定格式或未使用typescript
有没有办法测试日期格式 我试过下面的方法Angular 如何检查日期是否为特定格式或未使用typescript,angular,typescript,Angular,Typescript,有没有办法测试日期格式 我试过下面的方法 let newdate = new Date(myStringDate); Date.parse(myStringDate) result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}` 在这里,我将以dd/MM/yyyy格式获得结果。 现在我需要检查格式是否有效。请调查这一点,并为我提供一个合适的方式来检查格式 为我提供一个合适的方式来检查格式 下
let newdate = new Date(myStringDate);
Date.parse(myStringDate)
result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}`
在这里,我将以dd/MM/yyyy格式获得结果。
现在我需要检查格式是否有效。请调查这一点,并为我提供一个合适的方式来检查格式
为我提供一个合适的方式来检查格式
下面是一个使用力矩的示例:
export namespace Dates {
export const dateFormats = {
dateTimeFormat: 'DD/MM/YYYY HH:mm',
dateOnlyFormat: 'DD/MM/YYYY',
monthYearFormat: 'MM/YYYY',
isoFormat: 'YYYY-MM-DD HH:mm:SS ', // Corresponds to '2016-01-04T13:00:00Z'
}
export function toDate(value: string,
/**
* The default has *all* the formats
* - This is because strict date type validations
* - are done by passing in explicit limited sets.
**/
formats = [
dateFormats.dateTimeFormat,
dateFormats.dateOnlyFormat,
dateFormats.isoFormat,
dateFormats.monthYearFormat,
]
): { valid: boolean, date: Date | null } {
if (!value || !value.trim().length) {
return { valid: true, date: null };
}
let trimmed = value.trim();
if (!formats.some(format => format.length == trimmed.length)) {
return { valid: false, date: null };
}
// http://momentjs.com/docs/#/parsing/string-formats/
let date = moment(value, formats, true);
if (!date.isValid()) {
return { valid: false, date: null };
}
return { valid: true, date: date.toDate() };
}
}
可以根据需要随意更改日期格式最便宜的实现方法是使用正则表达式检查返回的格式
下面是正则表达式
var pattern = new RegExp('^((([1-2][0-9])|(3[0-1]))|([1-9]))/((1[0-2])|([1-9]))/[0-9]{4}$');
上面的模式将检查以下格式
- 1991年1月1日
- 1991年1月12日
- 1991年1月30日
- 1991年12月30日
增加奖金
正则表达式还可以检查不正确的日期,例如将32作为日期,或者在月份中为0,甚至是大于12的月份