以前的日历日期未按预期出现,需要解决方法

Previous Calendar date not coming as expected, need a workaround

The following code gives incorrect output - 29/01/2015, should give 29/12/2015. Please provide a work around to get the correct value.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CheckTime{

public static void main(String... x) throws Exception{

    DateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
    Date date = formatter.parse("31/12/2015");
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, -1);
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH);

    System.out.println(day+"/"+month+1+"/"+year);
}
}

格式模式错误

正如评论所讨论的那样,格式模式在本应使用大写 MM (month-in-year) 的地方使用了小写 mm (minute-in-hour)。

java.time

Java 8 及更高版本附带 java.time 框架,该框架取代了问题中使用的旧 date-time 类。这些新 类 是 巨大的 改进。避旧

在新的 类 中,有一个跟踪没有 time-of-day 或时区的 date-only 值:LocalDate

标准 ISO 8601 格式默认用于解析和生成 date-time 值的字符串表示形式。由于您的字符串输入格式不同,我们必须指定编码模式。

String input = "31/12/2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "dd/MM/yyyy" );
LocalDate localDate = LocalDate.parse ( input, formatter );

我们可以轻松找到前几天和后几天。注意使用 immutable objects pattern. Rather than alter member fields of an object, we create a new object based on the old object’s values. Much safer for value objects 例如 date-time.

LocalDate previousDay = localDate.minusDays ( 1 );
LocalDate nextDay = localDate.plusDays ( 1 );

转储到控制台。

System.out.println ( "localDate: " + localDate + "  previousDay: " + previousDay + "  nextDay: " + nextDay  );

localDate: 2015-12-31 previousDay: 2015-12-30 nextDay: 2016-01-01