Is there a way to validate time using Moment JS?

前端 未结 2 1557
囚心锁ツ
囚心锁ツ 2021-02-19 06:24

Is there a way to validate if the String passed as time is valid using Moment JS?

The operations moment(\"2014-12-13 asdasd\",\"YYYY-MM-DD LT\").isValid() o

2条回答
  •  粉色の甜心
    2021-02-19 06:40

    const allPossibleFormats = [
      'D MMMM YYYY',
      'D MMMM YYYY HH:mm',
      'DD-MM-YY',
      'DD-MM-YYYY',
      'DD.MM.YYYY',
      'DD.MM.YYYY HH:mm',
      'DD/MM/YY',
      'DD/MM/YYYY',
      'DD/MM/YYYY HH:mm:ss',
      'HH:mm:ss',
      'M/D/YYYY',
      'D/M/YYYY',
      'MM-DD-YY',
      'MM-DD-YYYY',
      'MM-DD-YYYY HH:mm:ss',
      'MM/DD/YY',
      'MM/DD/YYYY',
      'MM/DD/YYYY HH:mm:ss',
      'MMM D YYYY',
      'MMM D YYYY LT',
      'MMMM Do YYYY',
      'MMMM Do YYYY LT',
      'YYYY-DD-MM HH:mm:ss',
      'YYYY-MM',
      'YYYY-MM-DD',
      'YYYY-MM-DD HH:mm',
      'YYYY-MM-DD HH:mm:ss',
      'YYYY-MM-DD LT',
      'YYYY-MM-DD h:mm:ss A',
      'YYYY-MM-DDTHH:mm:ssZ',
      'ffffd, MMM D YYYY LT',
      'ffffdd D MMMM YYYY HH:mm',
      'ffffdd, MMMM Do YYYY LT'
    ];
    
    moment('Chicago Illinois 46702', allPossibleFormats, true).isValid(); // false
    moment('18/01/1944', allPossibleFormats, true).isValid(); // true
    moment('22-10-2020', allPossibleFormats, true).isValid(); // true
    moment('1944-01-18 12:00:00', allPossibleFormats, true).isValid(); // true
    moment('2001-01-01 00:00:00', allPossibleFormats, true).isValid(); // true
    moment('2001-01', allPossibleFormats, true).isValid(); // true

提交回复
热议问题