How can I increment a date by one day in Java?

前端 未结 28 1784

I\'m working with a date in this format: yyyy-mm-dd.

How can I increment this date by one day?

28条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 07:22

    If you want to add a single unit of time and you expect that other fields to be incremented as well, you can safely use add method. See example below:

    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    cal.set(1970,Calendar.DECEMBER,31);
    System.out.println(simpleDateFormat1.format(cal.getTime()));
    cal.add(Calendar.DATE, 1);
    System.out.println(simpleDateFormat1.format(cal.getTime()));
    cal.add(Calendar.DATE, -1);
    System.out.println(simpleDateFormat1.format(cal.getTime()));
    

    Will Print:

    1970-12-31
    1971-01-01
    1970-12-31
    

提交回复
热议问题