0

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"

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
Leo Ribeiro
  • 1,195
  • 1
  • 14
  • 25
  • When you say "didn't work", what does that mean? Are you getting an exception, is the output not what you're expecting? Also, I notice that the pattern you're using to parse is your desired *output* format, you need a pattern that will match the *input* format. – blm Oct 07 '15 at 18:17
  • It says that couldn't be parsed. "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" – Leo Ribeiro Oct 07 '15 at 18:18
  • I'll try the input format.. – Leo Ribeiro Oct 07 '15 at 18:20
  • It worked :D!!! Thanks @blm!! – Leo Ribeiro Oct 07 '15 at 18:31
  • I'm glad it worked but you might want to edit your comment to clean up the language. – blm Oct 07 '15 at 18:35
  • @gord-thompson do you have another tip to avoid this exception? – Leo Ribeiro Nov 08 '15 at 15:44

1 Answers1

1

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!!!

Community
  • 1
  • 1
Leo Ribeiro
  • 1,195
  • 1
  • 14
  • 25