繁体   English   中英

日期时间格式 (yyyy-mm-ddThh:mm:ss) ISO8601 格式的正则表达式

[英]regular expression for datetimeformat (yyyy-mm-ddThh:mm:ss) ISO8601 format

我想验证日历 object 应该是 2014-05-05T12:12:30。如何使用正则表达式验证这个

Adam Yost 的回答中的正则表达式很接近,但在 T 之前缺少右括号...没有足够的代表发表评论所以这里是更正后的版本:

(19|20)[0-9][0-9]-(0[0-9]|1[0-2])-(0[1-9]|([12][0-9]|3[01]))T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]

此正则表达式将仅匹配该格式的日期,但有一些限制:

(19|20)[0-9][0-9]-(0[0-9]|1[0-2])-(0[1-9]|([12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]

这匹配年份 1900-2099,12 个月,最多 31 天,24 小时制,最多 59 分钟,最多 59 秒

应该注意的是,如果您希望验证某个日期是否是真正有效的日期(即不是 2 月 30 日),您将需要一个复杂得多的正则表达式,或者一些简单的代码来环绕它。

正则表达式不是满足此要求的正确工具

您应该为此要求使用日期时间 API。 只需使用LocalDateTime#parse来解析您的日期时间字符串,如果验证失败,将抛出DateTimeParseException

请注意, java.time API 基于ISO 8601 ,因此您不需要DateTimeFormatter来解析已经采用 ISO 8601 格式的日期时间字符串(例如,您的日期时间字符串2014-05-05T12:12:30 ).

演示

import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;

class Main {
    public static void main(String args[]) {
        // Test date-time strings
        String[] arr = { "2014-05-05T12:12:30", "2014-05-05T123:12:30" };
        for (String strDateTime : arr) {
            System.out.print("Validating " + strDateTime);
            try {
                LocalDateTime.parse(strDateTime);
                System.out.println(" => It is a valid date-time string");
            } catch (DateTimeParseException e) {
                System.out.println(" => Validation failed, Error: " + e.getMessage());
                // throw e
            }
        }
    }
}

Output :

Validating 2014-05-05T12:12:30 => It is a valid date-time string
Validating 2014-05-05T123:12:30 => Validation failed, Error: Text '2014-05-05T123:12:30' could not be parsed at index 13

Trail:Date Time了解有关现代日期时间 API 的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM