如何使用typescript

时间:2017-12-19 19:54:10

标签: angular typescript

有没有办法测试日期格式。

我试过下面的方法

let newdate = new Date(myStringDate);
Date.parse(myStringDate)
result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}`

这里我将得到dd / MM / yyyy格式的结果。 现在我需要检查格式是否有效。请仔细研究并提供一种检查格式的合适方法。

2 个答案:

答案 0 :(得分:1)

  

为我提供了一种检查格式的合适方法。

以下是使用moment的示例:

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() };
  }
}

随意根据需要更改日期格式

答案 1 :(得分:0)

最便宜的实现方法是使用正则表达式来检查返回的格式

这是正则表达式

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日
  • 30/1/1991
  • 30/12/1991

已添加奖金 正则表达式还可以检查错误的日期,例如将32作为日期,或者将月份中的0或甚至是大于12的月份。