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

前端 未结 28 1859

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

How can I increment this date by one day?

28条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 07:06

    Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the Calendar.add method (presumably the only easy way).

    public class DateUtil
    {
        public static Date addDays(Date date, int days)
        {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, days); //minus number would decrement the days
            return cal.getTime();
        }
    }
    

    To add one day, per the question asked, call it as follows:

    String sourceDate = "2012-02-29";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date myDate = format.parse(sourceDate);
    myDate = DateUtil.addDays(myDate, 1);
    

提交回复
热议问题