I'm trying to parse a date time object in Groovy running on Java 7 with strict/exact parsing.
I've tried using SimpleDateFormat
with setLenient
set to false
but it is still too lenient, e.g. parsing value 2018-8-2
with format yyyy-MM-dd
still succeeds (and returns the wrong date).
I came across a potential answer here: Java: How to parse a date strictly?
However the environment I'm working on does not allow me to invoke static methods for security reasons, preventing me from using Joda's
DateTimeFormat.forPattern("yyyy-MM-dd")
Given this restriction, how can I do an exact/strict parse of a DateTime string in Groovy?
You could use DateTimeFormatterBuilder
from Joda-Time (here), with a simple regex to broadly confirm the format. (There is a better way here but it uses static methods.)
Full example here.
Consider:
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
}
Usage:
assert new DateTime(2018,8,2,0,0) == getDateTime('2018-08-02')
assert null == getDateTime('18-08-02')
assert null == getDateTime('2018-8-02')
assert null == getDateTime('2018-08-2')