-4

I'm trying to parse a string "Nov 6, 2017 11:47:53 AM" to a Date through SimpleDateFormat but I'm not able to find the correct format to use. Someone can help me?

Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
  • 1
    please show what you have tried, and what was the error/problem. The way you ask now you want somebody not to help you, but to do it instead of you. – Vladyslav Matviienko Nov 06 '17 at 11:31
  • 1
    please paste some code here to identify your problem. – Ratilal Chopda Nov 06 '17 at 11:33
  • A tip for you: You can find your answer faster by searching existing questions and answers than by waiting for someone to type a new answer here. – Ole V.V. Nov 06 '17 at 11:35
  • I recommend you consider [the modern Java date and time API known as JSR-310 or `java.time`](https://docs.oracle.com/javase/tutorial/datetime/) rather than the outdated `Date` and `SimpleDateFormat`. I know it’s not built-in on most Android phones yet, but you can get [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) and start using it. – Ole V.V. Nov 06 '17 at 11:37
  • Possible duplicate of [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion). – Ole V.V. Nov 06 '17 at 11:39

3 Answers3

2

The template that should be able to parse this text is MMM d, yyyy hh:mm:ss a assuming that the hours of the day are in the range of 1-12. If they are in the range of 0-11 replace hh by KK.

Lothar
  • 5,323
  • 1
  • 11
  • 27
1

Use "MMM dd, yyyy hh:mm:ss aaa"

public class Tester {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Date date = new Date();
        //Nov 6, 2017 11:47:53 AM
        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
        //sdf.parse(source);
        System.out.println(sdf.format(date));
    }

}

Output :

Nov 06, 2017 04:35:20 AM

Max08
  • 955
  • 1
  • 7
  • 16
0

Even on Android it’s worth considering trashing the long outdated classes Date and in particular SimpleDateFormat, it’s shown to be quite troublesome. I recommend getting ThreeTenABP. It will allow you to use the modern Java date and time API on Android (that’s three-ten for JSR-310, where the API was first described).

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM d, uuuu h:mm:ss a", Locale.ENGLISH);
    String stringToParse = "Nov 6, 2017 11:47:53 AM";
    LocalDateTime dateTime = LocalDateTime.parse(stringToParse, dtf);

The result is a LocalDateTime of 2017-11-06T11:47:53.

If you absolutely need an old-fashioned Date object for some legacy API, you may do:

    Date oldfashionedDate = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());

There is much more about using ThreTenABP in this question: How to use ThreeTenABP in Android Project.

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