2016-06-27 47 views
-5

我有一个日期字符串,“2016-6-26”,我想与当前日期进行比较,如果我的日期是等于或大于,那么我想要做的当前日期做一些任务。 我已经实现了下面的代码,但它总是给我有效的我选择的任何日期。Date.after不工作对我

String[] parts = date.split("-"); //where date is 2016-6-26 
    String part1 = parts[0]; //2016 
    String part2 = parts[1]; //6 
    String part3 = parts[2]; //26 
    String valid_until =part3+"/"+part2+"/"+part1; //"26/06/2016";  // "28/02/2016"; 
    Log.d("soh_valid", valid_until); 
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); 

    Date strDate = null; 
    try { 
     strDate = sdf.parse(valid_until); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    if (new Date().after(strDate)) { 
     Log.d("new_date", String.valueOf(new Date())); 
    Toast.makeText(VASActivity.this,"valid",Toast.LENGTH_SHORT).show(); 
    }else{ 
     Toast.makeText(VASActivity.this,"Not valid",Toast.LENGTH_SHORT).show(); 
    } 

我在做什么错在这里? 有什么建议吗?

+0

解析是否工作?因为原始字符串中的“6”不会像您所期望的那样奇迹般地变成“06”。 – f1sh

+1

与你的问题没有关系,但为什么不使用'new SimpleDateFormat(“yyyy-MM-dd”);'而不是分割和重新格式化? –

+0

@ f1sh我加月份0,但它不工作 –

回答

0

,你需要不拆“ - ”,然后用追加“/”

String d="2016-6-26"; 
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-dd"); 
     Date date1 = sdf.parse(d); 
     Date currentDate=new Date(); 
     if(date1.equals(currentDate) || date1.after(currentDate)) 
     { 
      //your logic here 
     } 
+0

月(''6'')不适用这种模式(''MM'')。 – f1sh

+0

@ f1sh我的不好,修正了。谢谢你让我知道 – SpringLearner

+0

@ f1sh不正确:[它在这里说](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)“为了解析,模式的数量除非需要分隔两个相邻的字段,否则将忽略字母。“ –

1

您的要求是:

如果我的日期是等于或大于我想要做的当前日期做一些任务

你的代码是:

if (new Date().after(strDate)) { 
    // Do stuff since valid 
} 

然而,documentation for after状态:

public boolean after(Date when) 
    Tests if this date is after the specified date. 
Returns: 
    true if and only if the instant represented by this Date object is 
    strictly later than the instant represented by when; false otherwise. 

所以,这是真的,如果当前日期(通过new Date GOT)比你的日期,你的要求正好相反越大。所以,你应该use before

+0

我之前使用的日期大于当前日期,但它不适用于当前日期。关于当前日期 –

+0

您可以说'if(!new Date()例如,.after(strDate))'或'if(new Date()。equals(strDate)|| new Date()。before(strDate))''。 –