我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
在Java 8中简单的方法是:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
其他回答
看看Joda-Time (https://www.joda.org/joda-time/)。
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime date = parser.parseDateTime(dateString);
String nextDay = parser.print(date.plusDays(1));
我更喜欢使用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对象,并没有对前一个对象本身进行更改。
如果您想添加一个时间单位,并且希望其他字段也增加,则可以安全地使用add方法。请看下面的例子:
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()));
将打印:
1970-12-31
1971-01-01
1970-12-31
如果你使用的是Java 8, Java .time. localdate和Java .time.format. datetimeformatter可以让这个工作变得非常简单。
public String nextDate(String date){
LocalDate parsedDate = LocalDate.parse(date);
LocalDate addedDate = parsedDate.plusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
return addedDate.format(formatter);
}
让我们来澄清一下这个用例:您希望执行日历算术,并以java.util.Date开始/结束。
一些方法:
使用SimpleDateFormat转换为字符串并返回:这是一种效率低下的解决方案。 转换为LocalDate:您将丢失任何时间信息。 转换为LocalDateTime:这涉及更多步骤,您需要考虑时区。 使用Date.getTime()转换为epoch:这很有效,但你是用毫秒计算的。
考虑使用java.time.Instant:
Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);