Android:如何将字符串转换为日期? [英] Android: How can I Convert String to Date?

查看:93
本文介绍了Android:如何将字符串转换为日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次用户启动应用程序时,我将当前时间存储在数据库中.

I store current time in database each time application starts by user.

Calendar c = Calendar.getInstance();
    String str = c.getTime().toString();
    Log.i("Current time", str);

在数据库端,我将当前时间存储为字符串(如您在上面的代码中看到的).因此,当我从数据库加载它时,我需要将它转换为 Date 对象.我看到了一些样本,他们都使用了DateFormat".但我的格式与日期格式完全相同.所以,我认为没有必要使用DateFormat".我说得对吗?

In database side, I store current time as string (as you see in above code). Therefore, when I load it from database, I need to cast it to Date object. I saw some samples that all of them had used "DateFormat". But my format is exactly as same as Date format. So, I think there is no need to use "DateFormat". Am I right?

有没有办法直接将这个 String 转换为 Date 对象?我想将此存储的时间与当前时间进行比较.

Is there anyway to directly cast this String to Date object? I want to compare this stored time with current time.

谢谢

======>更新

谢谢亲爱的朋友们.我使用了以下代码:

Thanks dear guys. I used following code:

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;            

   }

推荐答案

从字符串到日期

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

从日期到字符串

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = new Date();  
    String dateTime = dateFormat.format(date);
    System.out.println("Current Date Time : " + dateTime); 
} catch (ParseException e) {
    e.printStackTrace();  
}

这篇关于Android:如何将字符串转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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