Tuesday, September 25, 2018

How do we convert ISO date format to millis in Java?

The code is like below. Works perfect.

private void setTimestamp(String timeCreated) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    try {
        Date timeCreatedDate = dateFormat.parse(timeCreated);
        timeStamp = (String) DateUtils.getRelativeTimeSpanString(timeCreatedDate.getTime(),
                                  System.currentTimeMillis(),
                                  DateUtils.SECONDS_IN_MILLIS);
    } catch ( ParseException e) {}
}

there are also one line solutions, but the above looks OK. Please note its Z in quotes. Else it gives parse exception.

references:
https://stackoverflow.com/questions/26519867/how-to-convert-iso8601-format-into-milliseconds?noredirect=1

No comments:

Post a Comment