Leo Ribeiro
Leo Ribeiro

Reputation: 1255

How to convert string values to dates in Java?

I'm trying to convert some date values from access (MDB) database.

I'm getting this: 'Tue May 17 08:29:00 BRT 2011'. But I want this: '2011-05-17 08:29:00'.

I already tried to use JAVA 8 new DateTime classes but didn't work.

Here is what I tried:

public class DateHelper {

    LocalDateTime dateTime;

    public DateHelper(String dateTime) {
        this.convertStringToDateTimeDeclaration(dateTime);
    }

    protected void convertStringToDateTimeDeclaration(String dateTime){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        this.dateTime = LocalDateTime.parse(dateTime, formatter);
    }

    public String getDateTime(){
        return dateTime.toString();
    }
}

but I get

"Exception in thread "JavaFX Application Thread" java.time.format.DateTimeParseException: Text 'Tue May 17 08:29:00 BRT 2011' could not be parsed at index 0"

Upvotes: 0

Views: 307

Answers (1)

Leo Ribeiro
Leo Ribeiro

Reputation: 1255

As @blm suggested:

I had just to match the input patterns like this:

protected void convertStringToDateTimeDeclaration(String dateTime){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy").;
        this.dateTime = LocalDateTime.parse(dateTime, formatter).withLocale(Locale.US);
    }

edit:

Added '.withLocale(Locale.US)' in the end of the LocalDateTime method chain to avoid the DateTimeParseException.

Thanks!!!

Upvotes: 1

Related Questions