3

I am using SimpleDateFormat class to parse date as follows :

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

But, getting the Parse exception error as follows :

java.text.ParseException: Unparseable date: "2015-09-16 10:21 AM" (at offset 16)

I have checked another format as a argument in SimpleDateFormat class is : "yyyy-MM-dd HH:mm:ss a" but, still same error is coming.

Is there any other datetime format I have to pass as a argument of SimpleDateFormat class ?

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
Jaimin Modi
  • 1,530
  • 4
  • 20
  • 72

3 Answers3

2

Try this if your input has not second value ..

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm a");

And if it has second value also then use this

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");

otherwise above one

For More detail....

MPG
  • 785
  • 6
  • 20
2

As you have said in the above comments, you use a TimePicker for choosing a date time and parse it. And you said that you also want the second. But apparently, TimePicker doesn't include the second. So how are you going to know what second the user wants? I guess 0. You can insert a string into the correct position to make it work. In you case you should insert ":00" in index 16. Just use a StringBuilder!

StringBuilder builder = new StringBuilder("2015-09-16 10:21 AM");
builder.insert (16, ":00");
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Without the `:ss` the seconds would default to 0. There should be no need to insert `:00` in the data and `:ss` in the pattern, unless the pattern is also used elsewhere with seconds input. – headuck Sep 16 '15 at 05:30
  • @headuck Well yes... you are right. But if you insert the string the seconds is not limited to 0. – Sweeper Sep 16 '15 at 05:31
1

TimePicker widget doesn't provide year-month-day , it only provide hour and minutes

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");

To get year-month-day you have to use DatePicker widget

Sanjeev
  • 4,255
  • 3
  • 28
  • 37
  • If you are using TimePicker widget it will only provide time not year month and day use SimpleDateFormat formatter = new SimpleDateFormat(" HH:mm a"); to get year month and day you have to use DatePicker – Sanjeev Sep 16 '15 at 05:11
  • You are right, I am using DatePicker also and storing date value in Date field and using TimePicker to store time in Time field in database and combining both the values when i am retrieving it from database. Thanks for your efforts. – Jaimin Modi Sep 16 '15 at 06:07