How to check Regular Expression for Timestamp in GWT?

后端 未结 3 1582
暖寄归人
暖寄归人 2021-01-06 20:28

What will be the regular expression for following Timestamp format

YYYY-MM-DD HH:mm:ss.S

YYYY-MM-DD HH:mm:ss.S AM/PM

YYYY-MM-DD HH:mm:ss.S AM/PM Z

YYYY-MM         


        
相关标签:
3条回答
  • 2021-01-06 20:56

    Apart from Datejs which relays on js to check a date-string, Gwt comes with DateTimeFormat to parse date-string and format dates with support for locales. It raises a IllegalArgumentException in the case the parsed string doesn't match the expected format .

    String dateStr = "2011-04-21 20:37:36.999 -0800";
    String fmt = "yyyy-MM-dd HH:mm:ss.S Z"; // your 4th case: YYYY-MM-DD HH:mm:ss.S Z
    DateTimeFormat format = DateTimeFormat.getFormat(fmt);
    try {
      Date date = format.parse(dateStr);
      System.out.println("Validated: " + date);
    } catch (IllegalArgumentException e) {
      System.out.println("Validation error: " + e.getMessage());
    }
    
    dateStr = "2011-04-21 08:37:36.999 PM -0800"; // your 3rd case YYYY-MM-DD HH:mm:ss.S AM/PM Z
    fmt = "yyyy-MM-dd hh:mm:ss.S a Z";
    format = DateTimeFormat.getFormat(fmt);
    try {
      Date date = format.parse(dateStr);
      System.out.println("Validated: " + date);
    } catch (IllegalArgumentException e) {
      System.out.println("Validation error: " + e.getMessage());
    }
    

    You dont say whether the format string is fixed or it can be provided in runtime before performing the validation. So in the second case you need to use replace to change 'Y' by 'y', and 'AM/PM' to 'a' which are the symbols used in DateTimeFormat

    0 讨论(0)
  • 2021-01-06 21:14

    Just something simple as only describing the pattern like this:

    ^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}(?: [AP]M)?(?: [+-]\d{4})?$
    

    as any tentative of real date validation with a regex sounds inherently wrong.

    I got the uppercase Z as RFC822 timezone, regex needs changes to comply to TZDs or general textual time zones.

    0 讨论(0)
  • 2021-01-06 21:14

    I would say use Datejs

    Otherwise you will need to do a lot of coding, and regex is not the best for verifying timestamps and if it is valid. Datejs will check the date validity, and from that you will receive a Date object or null (if it is invalid!).

    Date.parse("2013-02-02 12:01:01.000", "yyyy-MM-dd HH:mm:ss.u");

    For more information see:

    Datejs API documentation

    Datejs Format spec

    0 讨论(0)
提交回复
热议问题