ISO Date/Time in java

took me a while to figure this one out, you’d think getting a standarized date/time would be a bit simpler…

put the following in a class

private final static SimpleDateFormat dateFormat;
static {
    //as per ISO 8601
    dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    //make sure the formatter requires an exact string
    dateFormat.setLenient(false);
    //set "timezone" to Universal Time Coordinates (GMT adjusted by leap seconds)
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}

and the following elsewhere in the class:

//to create a string
String nowString = dateFormat.format(new Date());
//to parse a proper string to a date
Date nowDate = dateFormat.parse(nowString);

Leave a comment

  • Categories

  • Need Code Written?

  • Need a Coding Job?

  • Tags

  • Archives