1

I have a date and time picker and I build a string date using these two. Here's a sample date and time string.

"11/6/2013 09:23"

Now I need to convert them into a date and convert them to this format "yyyy-MM-dd'T'HH:mm:ss.SSS".

My problem is I'm having this error in my logcat:

11-06 21:23:53.060: E/Error(26255): Unparseable date: "11/6/2013 09:23" (at offset 2)

I'm using this code to do the conversion of string to date, and the date to a formatted string.

Date d = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault()).parse(etaToDeliverArrivedAtShipper.getText().toString());
ETAtoNextStop = d.toString();

When I use new Date and get the current date, it works fine. I guess the format of my string is wrong. But I'm displaying it on an edittext in that format. I want to stay it in that way. Is there anyway to convert this string format to a date? Any ideas guys? Thanks!

Luke Villanueva
  • 2,030
  • 8
  • 44
  • 94

3 Answers3

0

This is simply because your pattern is not matching the date string you are trying to parse. There are 3 errors in your pattern :

  • You use MM which means the month should be on two digits, while in the date it is only 1 digit
  • You use .SSS which means there are milliseconds but your date is not that precise
  • You are using the wrong delimiter

So the right pattern should be : yyyy/M/dd HH:mm:ss

To get the desired format, then create a new SimpleDateFormat object with the desired pattern and use the parse(Date) method giving it the Date object previously returned by parse().

Mickäel A.
  • 9,012
  • 5
  • 54
  • 71
0

I think you are trying to do 2 things at once. In order to convert any String to another String in a different format you need to:

Parse the string with a DateFormat containing the current format, this returns a Date; then take your newly obtained Date and format it under the desired DateFormat

SimpleDateFormat formatOne = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = formatOne.parse(etaToDeliverArrivedAtShipper.getText().toString());
SimpleDateFormat formatTwo = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS",Locale.getDefault());
String result = formatTwo.format(date)
javaNoober
  • 1,338
  • 2
  • 17
  • 43
0

you are trying to parse in yyyy-MM-dd'T'HH:mm:ss.SSS but it is not. it is probably yyyy/M/dd HH:mm:ss

What you probably want is:

Date d = new SimpleDateFormat("yyyy/M/dd HH:mm:ss", Locale.getDefault()).parse(etaToDeliverArrivedAtShipper.getText().toString());
ETAtoNextStop = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault()).format(d);
Ivo
  • 18,659
  • 2
  • 23
  • 35