格式化日期时间字符串时间只 [英] Format a datetime string to time only

查看:135
本文介绍了格式化日期时间字符串时间只的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从一个SQLite数据库而出来的格式检索日期时间......

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

2011-01-24 02:45:00

在C#中,我可以简单地使用 DateTime.Parse(2011-01-24 2时45分00秒)的ToString(HH:MM)。为了得到字符串 02:45

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

时的一种方法,我,我可以做到这一点在Android的/ Java的?我的code在我的Andr​​oid应用程序看起来像这样...

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

编辑:由于双方doc_180和康斯坦丁波罗夫 - 给予帮助我理清问题的例子。部分的问题是,我是进口java.sql.Date而不是java.util.Date。我已经改变了周围的事物和它的工作完美的我了。

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.

推荐答案

您需要做到以下几点。

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.

这篇关于格式化日期时间字符串时间只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆