Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a datetime string to time only

I'm retrieving a datetime from a SQLite DB which comes out in the format...

2011-01-24 02:45:00

In C# I can simply use DateTime.Parse("2011-01-24 02:45:00").ToString("HH:mm") in order to get the string 02:45

Is their a way I can I do this in Android/Java? My code in my Android app looks like this...

// dateStr below is logging as correctly being yyyy-MM-dd HH:mm:ss format
String dateStr = cursor.getString(cursor.getColumnIndex("start_time"));
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String shortTimeStr = sdf.format(dateStr); // <-- throws IllegalArgumentException

EDIT: Thanks to both doc_180 and Konstantin Burov - the examples given have helped me sort out the problem. Part of the issue was that I was importing java.sql.Date instead of java.util.Date. I've changed things around and it's working perfectly for me now.

like image 419
Squonk Avatar asked Dec 05 '22 23:12

Squonk


1 Answers

You need to do the following.

try {
   Date date = null;
   date = df.parse("2011-01-24 02:45:00");
   SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
   String shortTimeStr = sdf.format(date);
   System.out.println(shortTimeStr);
} catch (ParseException e) {
   // To change body of catch statement use File | Settings | File Templates.
   e.printStackTrace(); 
}

As I mentioned in comment, you should store the time as milliseconds instead of string. Otherwise, I do not see any other way than creating a middleman object Date.

like image 100
uncaught_exceptions Avatar answered Dec 08 '22 15:12

uncaught_exceptions