在 java 中使用 simpledateformat 添加 n 天

Add n number of days using simpledateformat in java

这里有一个 java 代码片段

import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
    Date date = new Date();
    int days = 5;
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String strDate= formatter.format(date.getTime() + (days*86400000));
    System.out.println(strDate);
}
}

添加 n 号。天到今天的日期。结果在 n=24 之前都是正确的,但在 n=24 之后给出上个月的结果。为什么会这样?

问题是 int is overflowing

考虑

    int days = 25;
    int d = days*86400000;
    System.out.println(d);

尝试

    int days = 25;
    long d = days*86400000L;
    System.out.println(d);

使用 days*86400000L 使其成为 long 计算,否则 int 值会溢出。

在您的代码中试试这个:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, 5); 

strDate = formatter.format(cal.getTime());

tl;博士

LocalDate               // Represent a date-only, without a time-of-day and without a time zone.
.now()                  // Capture the current date, as seen through your JVM’s current default time zone. Better to pass a `ZoneId` as the optional argument.
.plusDays( 5 )          // Add five days, returning a new `LocalDate` object. Per the Immutable Objects pattern, a new object is produced rather than changing (“mutating”) the original.
.format(                // Generate text representing the date value of our `LocalDate` object.
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Define a formatting pattern to suit your taste. Or call the `.ofLocalized…` methods to localize automatically. 
)                       // Returns a `String`.

java.time

Date class 表示 UTC 中的一个时刻,一个带有时间的日期,以及与 UTC 的偏移量为零。使用仅日期值时使用错误 class。

避免使用可怕的旧式日期时间 classes,例如 CalendarDateSimpleDateFormat。这些 classes 多年前被 java.time classes.

取代

不要将天数作为秒数或毫秒数来跟踪。日子不总是 24 小时,年也不总是 365 天。

LocalDate

而是使用 LocalDate class.

LocalDate today = LocalDate.now() ;
LocalDate later = today.plusDays( 5 ) ;

转换

最好完全避免遗留 classes。但如果你必须与尚未更新为 java.time classes 的旧代码进行互操作,你可以来回转换。调用添加到旧 classes 的新方法。

您需要为 Date 添加时间。我想你会想在一天的第一刻就去。我假设您想将日期设置为 UTC 而不是时区。我们必须通过一个 OffsetDateTime 对象来添加时间和偏移量。对于偏移量,我们使用常量 ZoneOffset.UTC。然后我们提取更基本的 Instant class 对象以转换为 java.util.Date

OffsetDateTime odt = OffsetDateTime.of( later , LocalTime.MIN , ZoneOffset.UTC ) ;  // Combine the date with time-of-day and with an offset-from-UTC.
Instant instant = odt.toInstant() ;  // Convert to the more basic `Instant` class, a moment in UTC, always UTC by definition.
java.util.Date d = java.util.Date.from( instant ) ;  // Convert from modern class to legacy class.

转向另一个方向:

Instant instant = d.toInstant() ;  // Convert from legacy class to modern class. 

关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes.

从哪里获得java.time classes?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.