1

I am making an app that use an API that give data with timestamps. The timestamp looks like:

Jul 20, 2018

I want to convert the string to a date. I try this code to parse the string to a Date.

DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
            Date date = dateFormat.parse("Jul 20, 2018");

but I even can't compile my code. Every time I try to parse a string with dateformat.parse() I got the following compile error:

java.text.ParseException

This even shows up when hovering above the the .parse() in code I browsed the whole day and tried a couple of different thing, but every time I use .parse() I got this error. I really dot know what to do any more.

I don't have the permission to post images yet, but you can watch the screenshot over here:https://i.stack.imgur.com/Jr7Ep.jpg

I am using Java 8 (with support for lambda notation). I am using androidx.legacy:legacy-support library, minimum API 19 and targetting API 28. (So the solution for this problem should support older devices as well)

Other things I tried but failed:

Android, How can I Convert String to Date?

Cant convert String to date in android

How to convert "2017-04-26T20:55:00.000Z" string to a Date in java android studio

Android date format parse throwing an Unhandled Exception

How to convert a date in this format (Tue Jul 13 00:00:00 CEST 2010) to a Java Date (The string comes from an alfresco property)

Convert string to Date in java

fupon
  • 43
  • 1
  • 6
  • 1
    The answer is in the 4th link you provided –  Jul 15 '18 at 19:11
  • 1
    your code compile correctly and gives correct answer. – alizeyn Jul 15 '18 at 19:16
  • 1
    Welcome to Stack Overflow. There’s a contradiction in your question. You say you can’t compile. And you say you get an exception, which can only happen at runtime, that is, after you have compiled successfully. You may be confused about the difference between compile-time errors and runtime errors? I am voting to close as unclear what you are asking. Please clarify in the question and I shall be happy to retract my close vote. – Ole V.V. Jul 15 '18 at 19:38
  • If it is true that you got the exception when running your program, then this is probably a duplicate ot [Java - Unparseable date](https://stackoverflow.com/questions/6154772/java-unparseable-date). – Ole V.V. Jul 15 '18 at 19:40
  • 2
    As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jul 15 '18 at 19:43
  • @OleVV OP is getting the "unhandled exception" error Android Studio shows, causing some confusion here between compiler errors and exceptions... It doesn't actually say they got an exception, it says they got an error about an exception – Tyler V Jul 15 '18 at 19:47
  • That’s one interpretation, @TylerV. If it is correct, I suggest that this question is a duplicate of [Unhandled Exception in Java](https://stackoverflow.com/questions/27890597/unhandled-exception-in-java) and of (the more Android-specific) [Cannot convert my String to Date](https://stackoverflow.com/questions/17399761/cannot-convert-my-string-to-date). Letting my close vote stand until the asker clarifies. – Ole V.V. Jul 16 '18 at 08:32

3 Answers3

1

That error is telling you that the function you are calling can throw a specific exception and you are not catching it (dateFormat.parse(...) can throw a ParseException error if the string cannot be parsed).

Try something like this

try {
    DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.US);
    Date date = dateFormat.parse("Jul 20, 2018");
}
catch(ParseException pe ) {
    // handle the failure
}
Tyler V
  • 9,694
  • 3
  • 26
  • 52
  • I managed to fix this problem, thanks to you. Only Date date, needed to be in the try. Not the whole dateFormat: DateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.US); try { Date date = dateFormat.parse("Jul 20, 2018"); } catch (java.text.ParseException e) { e.printStackTrace(); } if (game.getBuyonline().equals("true")) { onlineGames.add(game); } – fupon Jul 16 '18 at 11:56
1

java.time

    DateTimeFormatter dateFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.MEDIUM)
            .withLocale(Locale.US);
    LocalDate date = LocalDate.parse("Jul 20, 2018", dateFormatter); 

If you know that your date string is correct, just use the above code without any try-catch. If you need to validate the string (typically if it’s input from a user or from a different system), do use try-catch, either directly around the parsing or in the place in your code where it’s most convenient to handle any incorrect string. Example:

    try {
        LocalDate date = LocalDate.parse("Jul 20, 2018", dateFormatter);
    } catch (DateTimeParseException dtpe) {
        dtpe.printStackTrace();
    } 

I am using java.time, the modern Java date and time API, because it’s much nicer to work with, and the old SimpleDateFormat class in particular was renowned for being troublesome. One difference is: The old class threw a checked exception from parsing, which forced us to use either try-catch or a throws declaration on the surrounding method. The modern classes throw unchecked exceptions, which leaves it to us whether we want to catch and handle them or not. Don’t be fooled though: they are still exceptions and may cause your app to crash, so better handle them if there is any possibility that a string that is not in the correct format occurs.

As a side note rather use Java’s built-in date format than specifying your own. It’s simpler and less error-prone and easier to adapt to audiences of other languages and cultures. Your format coincides with the medium style format for the US locale, so I used this.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

you can use to new API of Java 8 .

LocalDate date = LocalDate.parse(CharSequence text);

text - the text to parse such as "2007-12-03T10:15:30", not null.

Zeuzif
  • 318
  • 2
  • 14
  • This Question is about date-only, not date-time. So `LocalDate` class. – Basil Bourque Jul 15 '18 at 23:39
  • Using java.time, the modern API, is a good idea. If the asker means “timestamp” seriously, your answer is close. If on the other hand we’re to believe that the string is `Jul 20, 2018`, @BasilBourque is correct that `LocalDate` is the right class to use. – Ole V.V. Jul 16 '18 at 08:34