How to format date in UTC format for yyyy-mm-dd

Asked

Viewed 1,488 times

0

I am working with the XML of an NF-e where the date fields are in UTC format (YYYY-MM-Ddthh:mm:ssTZD) and need to insert them into the database in yyyyyy-mm-dd format.

I’m using Simpledateformat to try to make the conversion, but I get one ParseException with the message "Unparseable date". My code looks like this:

public Date getDataEvento() {
    DateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    try {
        return dt.parse(this.dataEvento);
    } catch (ParseException e) {
        e.printStackTrace();
        return new Date();
    }
}
  • this.dataEvento is coming in string form? Unparseable means that the format you are passing does not match the one of the string you want to convert to Date type.

  • Exact. The string looks like this: "2017-09-01T12:13:20-03:00"

  • 1

    Take a look at the questions I’ve set, the second probably answers your question.

  • I don’t know why, but when I removed the "T" it worked. I did so this.dataEvento.replaceAll("T", " ")

  • It worked because its SimpleDateFormat uses "yyyy-MM-dd hh:mm:ss". If you used "yyyy-MM-dd'T'HH:mm:ss", would work with the "T". Another detail is that it is better to use HH instead of hh, because the lowercase h means "hour of am/pm" (values between 1 and 12, and "uncertain" behavior with values greater than 12, since there is no am/pm to solve the correct value). The capital H works with values between 0 and 23, and works better in your case.

  • Another detail is that the way it is, the offset (-03:00) is being ignored and you may end up with a date in another time zone if the default JVM Timezone is not one that uses -03:00. So in fact the SimpleDateFormat should wear yyyy-MM-dd'T'HH:mm:ssXXX - the X works in Java >= 7

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.