Created
March 19, 2018 00:31
-
-
Save ppazos/0ea846f607b978bd5a7d8eb92d1f3b38 to your computer and use it in GitHub Desktop.
Tests parsing datetimes for a date time validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.SimpleDateFormat | |
import java.text.ParseException | |
TimeZone.setDefault(TimeZone.getTimeZone("UTC")) | |
// casos: con o sin fraccion, con o sin timezone | |
def candidates = ['1981-10-24T09:59:00', | |
'1981-10-24T09:59:00Z', | |
'1981-10-24T09:59:00-03:00', | |
'1981-10-24T09:59:00.666', | |
'1981-10-24T09:59:00.666Z', | |
'1981-10-24T09:59:00.666-03:00'] | |
// el matcheo es parcial, si matchea la primera parte, descarta el resto, | |
// por eso los formatos mas especificos tienen que verificarse primero, | |
// por ejemplo yyyy-MM-dd'T'HH:mm:ss.SSS va a matchear 1981-10-24T09:59:00.666Z (ignora el Z) | |
// y tambien va a matchear 1981-10-24T09:59:00.666-03:00, ignora el -03:00, lo que genera | |
// una fecha invalida porque el resultado deberia estar en -3 y esta en Z. | |
// Should stay with the first match | |
def formats = ["yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", | |
"yyyy-MM-dd'T'HH:mm:ss.SSSX", | |
"yyyy-MM-dd'T'HH:mm:ss.SSS", | |
"yyyy-MM-dd'T'HH:mm:ss'Z'", | |
"yyyy-MM-dd'T'HH:mm:ssX", | |
"yyyy-MM-dd'T'HH:mm:ss"] | |
def d | |
for (String format : formats) | |
{ | |
for (String candidate : candidates) | |
{ | |
try | |
{ | |
SimpleDateFormat sdf = new SimpleDateFormat(format) | |
sdf.setLenient(false) // avoids heuristic parsing, enabling just exact parsing | |
d = sdf.parse(candidate) | |
println "'"+ candidate +"'\t matches '"+ format +"' "+ d | |
} | |
catch (ParseException e) | |
{ | |
println e.message +" >"+ format | |
} | |
} // for candidates | |
println "-------------" | |
} // for formats | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment