获取下个月的第一天

Sih*_*ovu 1 java calendar date

您好,我正在尝试在下面的代码中获取当前年份,但是上个月它返回 1970 年而不是 2020 年,这工作正常,但自从我们在 2020 年 1 月以来,它现在返回 1970 年的日期,请协助

  public String firstDateOfNextMonth(){
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      Calendar today = Calendar.getInstance();
      Calendar next = Calendar.getInstance();
      today.clear();
      Date date;

      next.clear();
      next.set(Calendar.YEAR, today.get(Calendar.YEAR));
      next.set(Calendar.MONTH, today.get(Calendar.MONTH)+ 1);
      next.set(Calendar.DAY_OF_MONTH, 1);


      date = next.getTime();

      Log.d(TAG, "The Date: " + dateFormat.format(date));
      return  dateFormat.format(date);

  }
Run Code Online (Sandbox Code Playgroud)

deH*_*aar 5

如果您有 Java 8 或更高版本,那么您已经java.time并且不必依赖过时的日期时间实现,您可以这样做:

public static String getFirstOfNextMonth() {
    // get a reference to today
    LocalDate today = LocalDate.now();
    // having today, 
    LocalDate firstOfNextMonth = today
            // add one to the month
            .withMonth(today.getMonthValue() + 1)
            // and take the first day of that month
            .withDayOfMonth(1);
    // then return it as formatted String
    return firstOfNextMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
Run Code Online (Sandbox Code Playgroud)

今天(2020-01-03)调用时会打印以下内容,例如System.out.println(getFirstOfNextMonth());

public static String getFirstOfNextMonth() {
    // get a reference to today
    LocalDate today = LocalDate.now();
    // having today, 
    LocalDate firstOfNextMonth = today
            // add one to the month
            .withMonth(today.getMonthValue() + 1)
            // and take the first day of that month
            .withDayOfMonth(1);
    // then return it as formatted String
    return firstOfNextMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
Run Code Online (Sandbox Code Playgroud)

如果您希望它在 API 级别 26 以下的 Android 中工作,您可能必须涉及外部库 ThreeTenAbp。它的使用在这个问题中进行了解释。

  • 它不仅短得多,而且首先比问题中的代码更清晰。谢谢。在微小细节部分,我的版本可能是 `YearMonth.now(ZoneId.systemDefault()).plusMonths(1).atDay(1).toString()`, (2认同)