严格解析日期时间,无需使用静态对象

时间:2018-07-31 19:15:00

标签: datetime groovy jodatime strict exact-match

我正在尝试使用严格/精确解析来解析在Java 7上运行的Groovy中的日期时间对象。

我尝试将SimpleDateFormat设置为setLenient的情况下使用false,但是它仍然太宽容,例如仍然可以成功解析格式为2018-8-2的值yyyy-MM-dd(并返回错误的日期)。

我在这里遇到了一个可能的答案: Java: How to parse a date strictly?

但是,由于安全原因,我正在使用的环境不允许我调用静态方法,这使我无法使用Joda的

DateTimeFormat.forPattern("yyyy-MM-dd")

鉴于此限制,如何在Groovy中对DateTime字符串进行精确/严格的解析?

1 个答案:

答案 0 :(得分:1)

您可以使用Joda-Time(here)中的 sub(".*?([^)]+)\\s\\(\\d+\\)$","\\1",x) [1] "WB" "WB" "NBIO" "CITG-TP" "BK-AR" ,并使用一个简单的正则表达式大致确认格式。 (有一种更好的方法here,但它使用静态方法。)

完整示例here

考虑:

DateTimeFormatterBuilder

用法:

def getDateTime(def s) {
    def result = null

    def regex = /^\d\d\d\d-\d\d-\d\d$/

    if (s ==~ regex) {
        // yyyy-MM-dd
        def formatter = new DateTimeFormatterBuilder()
                             .appendYear(4,4)
                             .appendLiteral('-')
                             .appendMonthOfYear(2)
                             .appendLiteral('-')
                             .appendDayOfMonth(2)
                             .toFormatter()
        try {
            result = formatter.parseDateTime(s)
        } catch (Exception ex) {
            // System.err.println "TRACER ex: " + ex.message
        }
    }

    return result
}