6

Getting parse exception when I'm applying a particular format to the date.

SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
try {
    String s=timeSlotsArrayList.get(position).getScheduledStartTime();
    Date d = df.parse(s);
    times.setText(df.format(d));
}
catch (ParseException e) {
    e.printStackTrace();
}

AM is getting instead of PM issue image

AM is getting instead of PM issue image

Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
Priyanka
  • 138
  • 2
  • 15
  • How did you format `df`? – Md. Asaduzzaman Feb 06 '20 at 10:18
  • Updated the code @Md.Asaduzzaman – Priyanka Feb 06 '20 at 10:20
  • Are those two different issues? How can you get any AM or PM in the image when you get a parse exception first? – Ole V.V. Feb 06 '20 at 15:48
  • 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. Feb 06 '20 at 15:48
  • Does this answer your (first) question? [Converting String to Date using SimpleDateFormat is returning random date \[duplicate\]](https://stackoverflow.com/questions/50513135/converting-string-to-date-using-simpledateformat-is-returning-random-date). Maybe in conjunction with this? [Date format conversion Android](https://stackoverflow.com/questions/6896635/date-format-conversion-android). – Ole V.V. Feb 06 '20 at 15:51
  • Does this answer your question? [What is this date format? 2011-08-12T20:17:46.384Z](https://stackoverflow.com/questions/8405087/what-is-this-date-format-2011-08-12t201746-384z) – Nadim Ansari Feb 12 '21 at 12:16

1 Answers1

6

You didn't apply correct format to your SimpleDateFormat. Use

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

And then parse time like below:

Date d = df.parse(s);

String time = new SimpleDateFormat("hh:mm a").format(d);
times.setText(time);
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
  • I need only time from the string,No need date – Priyanka Feb 06 '20 at 10:25
  • Worked but 12:30 is getting AM instead of PM. I added image below of my code. – Priyanka Feb 06 '20 at 10:33
  • Use `HH:mm:ss` instead of `hh:mm:ss` for 24 hour format – Md. Asaduzzaman Feb 06 '20 at 10:39
  • I got another issue related to the date. I want to reduce one day for particular date. But It's reducing for 1 month. df = new SimpleDateFormat("EEEE, dd MMMM YYYY"); Date prevDate = df.parse(dateText.getText().toString()); Calendar c = Calendar.getInstance(); c.setTime(prevDate); c.add(Calendar.DAY_OF_YEAR, -1); Date d=c.getTime(); dateText.setText(df.format(d)); – Priyanka Feb 06 '20 at 13:04