我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
Date today = new Date();
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1); // number of days to add
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is " + tomorrow);
这将给出明天的日期。C.add(…)参数可以从1更改为另一个数字,以获得适当的增量。
其他回答
看看Joda-Time (https://www.joda.org/joda-time/)。
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(dateString);
String nextDay = parser.print(date.plusDays(1));
试试这个方法:
public static Date addDay(int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, day);
return calendar.getTime();
}
我更喜欢使用Apache的DateUtils。查看这个http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html。它很方便,特别是当你必须在你的项目中多个地方使用它,而不想为此编写你的一行方法时。
API说:
addDays(Date Date, int amount):在返回新对象的日期上添加天数。
注意,它返回一个新的Date对象,并没有对前一个对象本身进行更改。
在java 8中,您可以使用java.time. localdate
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1); //Add one to the day field
您可以将其转换为java.util.Date对象,如下所示。
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
您可以将LocalDate格式化为字符串,如下所示。
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
像这样的东西应该可以达到目的:
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date