Format a datetime string to time only

别来无恙 提交于 2019-12-05 16:17:54
uncaught_exceptions

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.

SimpleDateFormat.format expects Date or Calendar as argument while you're passing a String. Convert the String into Date first.

String dateStr = cursor.getString(cursor.getColumnIndex("start_time"));
SimpleDateFormat toFullDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date fullDate = toFullDate.parse(dateStr);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String shortTimeStr = sdf.format(fullDate); 

And yeah, I'd rather stored date as long in the database, so getting a Date object then would be more trivial:

Long dateMilliseconds = cursor.getLong(cursor.getColumnIndex("start_time"));
Date fullDate = new Date(dateMilliseconds);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!