日期.在不为我工作之后



我有一个字符串中的日期,"2016-6-26",我想与当前日期进行比较,如果我的日期等于或大于当前日期,我想做一些任务。我已经实现了下面的代码,但它总是给我有效的任何日期我选择。

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();
    }

我在这里做错了什么?任何建议吗?

您的要求是:

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

你的代码是:

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

然而,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获得)大于您的日期(与您的要求完全相反),则为真。因此,您应该使用before

你不需要用"-"分隔然后再加上"/"

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
        }

最新更新