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

6
  • How did you format df? Commented Feb 6, 2020 at 10:18
  • Updated the code @Md.Asaduzzaman Commented Feb 6, 2020 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? Commented Feb 6, 2020 at 15:48
  • As an aside consider throwing away the long outmoded and notoriously troublesome SimpleDateFormat and friends, and adding 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. Commented Feb 6, 2020 at 15:48
  • Does this answer your (first) question? Converting String to Date using SimpleDateFormat is returning random date [duplicate]. Maybe in conjunction with this? Date format conversion Android. Commented Feb 6, 2020 at 15:51

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I need only time from the string,No need date
Worked but 12:30 is getting AM instead of PM. I added image below of my code.
Use HH:mm:ss instead of hh:mm:ss for 24 hour format
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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.