我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
请注意这一行增加了24小时:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
但是这条线增加了一天
cal.add( Calendar.DATE, 1 );
在夏令时改变的日子里(25或23小时),你会得到不同的结果!
其他回答
让我们来澄清一下这个用例:您希望执行日历算术,并以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);
构造一个Calendar对象并调用add(Calendar。目前为止,1);
在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"));
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更改为另一个数字,以获得适当的增量。
自Java 1.5以来,TimeUnit.DAYS.toMillis(1)对我来说看起来更干净。
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));