每次用户启动应用程序时,我会将当前时间存储在数据库中。
Calendar c = Calendar.getInstance();
String str = c.getTime().toString();
Log.i("Current time", str);
在数据库中,我将当前时间以字符串的形式存储(如上面的代码所示)。因此,当我从数据库加载它时,我需要将其转换为Date对象。我看到一些示例都使用了“DateFormat”。但是,我的格式与Date格式完全相同。因此,我认为没有必要使用“DateFormat”。我对吗?
有没有办法直接将这个字符串转换为Date对象?我想比较这个存储的时间和当前时间。
更新
谢谢大家。我使用了以下代码:
private boolean isPackageExpired(String date){
boolean isExpired=false;
Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");
if (new Date().after(expiredDate)) isExpired=true;
return isExpired;
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}
SimpleDateFormat.format()
会抛出异常。 - Someone SomewhereSimpleDateFormat dateFormat =new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'"", Locale.getDefault());
- Dheeraj Jaiswal