如何比较android中的日期值

时间:2014-11-18 18:07:36

标签: java android string date

我的textview需要显示考试截止日期。我的json将其作为字符串传递。然后我需要获取当前日期并在另一个textviwe

上显示剩余日期
String date    ="2014-11-12";  //ok
Date deadline  = //how to cast string to date  
//then how to get today and subtract 
textview1.setText(today);      
int remaindays = //how to get it    
textview2.setText("You have " +remaindays  +" days to exam");

2 个答案:

答案 0 :(得分:0)

试用此代码

 String date    ="2014-11-12"; 
 Date deadline; 
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
 Date strDate = sdf.parse(date);
 Long diff=-1;
 int diff=0;
 if (System.currentTimeMillis() > strDate.getTime()) {
    diff=System.currentTimeMillis()-strDate.getTime();
 }
 int remaindays = (int)diff/100/60/60/24
 textview2.setText("You have " +remaindays  +" days to exam");

答案 1 :(得分:0)

<强> 1。将字符串转换为日期

 String date = "2014-11-12";  
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd");  
        try {  
            Date date = format.parse(date);  
            System.out.println(date);  
        } catch (ParseException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
    }

<强> 2。得到今天的日期

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());

第3。日期的推广

long diff = date2.getTime() - date1.getTime();
int remaindays = (int)diff/100/60/60/24

这对你有意义吗?