将日期时间字符串格式化为仅时间
我正在从 SQLite DB 中检索日期时间,其格式为...
2011-01-24 02:45:00
在 C# 中,我可以简单地使用 DateTime.Parse("2011-01-24 02:45:00").ToString("HH :mm")
以获取字符串 02:45
他们是我可以在 Android/Java 中执行此操作的方法吗?我的 Android 应用程序中的代码如下所示...
// 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 和 Konstantin Burov - 给出的示例帮助我解决了问题。部分问题是我导入的是 java.sql.Date 而不是 java.util.Date。我已经改变了一些事情,现在它对我来说非常有效。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您传递字符串时,SimpleDateFormat.format 需要日期或日历作为参数。首先将字符串转换为日期。
是的,我宁愿将日期存储在数据库中,因此获取 Date 对象会更加简单:
SimpleDateFormat.format expects Date or Calendar as argument while you're passing a String. Convert the String into Date first.
And yeah, I'd rather stored date as long in the database, so getting a Date object then would be more trivial:
您需要执行以下操作。
正如我在评论中提到的,您应该将时间存储为毫秒而不是字符串。否则,除了创建中间人对象 Date 之外,我没有看到任何其他方法。
You need to do the following.
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.