当日期格式为 dd-MMM-yyyy 时无法找到两个日期之间的天数

Unable to find the number of days between two dates when date format is dd-MMM-yyyy

我正在使用以下代码解析类型为 23-May-2016 和 25-May-2017 的两个日期,然后我试图找出这两个日期之间的天数。

以下是我用来执行此操作的代码,

SimpleDateFormat format1 = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy");
Date validityDate = null;
Date nextDueDate = null;
try {
    validityDate = format1.parse(mValidity.getText().toString());
    nextDueDate = format2.parse(mDueDate.getText().toString());
    int validate = validate(validityDate, nextDueDate);
    Toast.makeText(getApplicationContext(),""+validate,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
    Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
}

validate方法如下,

public static int validate(Date valid, Date nextDueDate) {
    return (int) ((nextDueDate.getTime() - valid.getTime()) / (1000 * 60 * 60 * 24l));
}

当我尝试这样做时,我无法在索引偏移量 6 处进行解析。 我该如何解决这个问题?

您可以尝试使用此代码示例将 SimpleDateFormat 构造函数调用更改为 Locale 特定版本,以使月份字符串值(如 "May")可解析:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
Date validityDate = null;
Date nextDueDate = null;
try {
   validityDate = sdf.parse(mValidity.getText().toString());//string value like "25-May-2016"
   nextDueDate = sdf.parse(mDueDate.getText().toString());
   int validate = validate(validityDate, nextDueDate);
   Toast.makeText(getApplicationContext(),""+validate,Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
   Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_SHORT).show();
}

也没有必要在您的情况下创建两个相同的 SimpleDateFormat 实例

// 先获取格式

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");

// 定义日期

  Date d1 = new Date("01/01/2007 12:00:00");
  Date d2 = new Date("01/02/2007 12:00:00");

//设置时间

Calendar cal1 = Calendar.getInstance();cal1.setTime(d1);
  Calendar cal2 = Calendar.getInstance();cal2.setTime(d2);

//创建这个

 printOutput("Manual   ", d1, d2, calculateDays(d1, d2));

//调用

private static void printOutput(String type, Date d1, Date d2, long result) {
  System.out.println(type+ "- Days between: " + sdf.format(d1)
                    + " and " + sdf.format(d2) + " is: " + result);
}

在 Java 8 中,您可以使用新的日期和时间做一些更简单的事情 API:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
    LocalDate date1 = LocalDate.parse("23-May-2016", formatter);
    LocalDate date2 = LocalDate.parse("25-May-2017", formatter);
    System.out.println(ChronoUnit.DAYS.between(date1, date2));