简体   繁体   English

在Java中使用simpledateformat增加n天

[英]Add n number of days using simpledateformat in java

We have a java code snippet here 我们在这里有一个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);
}
}

to add n no. 加n号 of days to today's date. 到今天为止的天数。 The result will be correct upto n=24 but gives previous month' after n=24 . 结果将是正确的,直到n=24但在n=24之后给出上个月。 Why it is so? 为什么会这样呢?

The problem is the the int is overflowing 问题是int is overflowing

consider 考虑

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

try 尝试

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

tl;dr tl; dr

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 java.time

Date class represents a moment in UTC, a date with a time-of-day, and an offset-from-UTC of zero. Date类表示UTC中的时刻,具有时间的日期以及与UTC的偏移量为零。 Wrong class to use when working with date-only values. 使用仅日期值时使用了错误的类。

Avoid using the terrible old legacy date-time classes such as Calendar , Date , and SimpleDateFormat . 避免使用可怕的旧旧式日期时间类,例如CalendarDateSimpleDateFormat These classes were supplanted years ago by the java.time classes. 这些类在几年前被java.time类所取代。

Do not track days as a count of seconds or milliseconds. 不要以秒或毫秒为单位来跟踪天。 Days are not always 24 hours long, and years are not always 365 days long. 日子并非总是24小时长,几年也不总是365天长。

LocalDate

Instead, use LocalDate class. 而是使用LocalDate类。

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

Convert 兑换

Best to avoid the legacy classes altogether. 最好完全避免使用遗留类 But if you must interoperate with old code not yet updated to java.time classes, you can convert back-and-forth. 但是,如果必须与尚未更新为java.time类的旧代码进行互操作,则可以来回转换。 Call new methods added to the old classes. 调用添加到旧类中的新方法。

For Date you need to add a time-of-day. 对于Date您需要添加一个时间。 I expect you will want to go with the first moment of the day. 我希望您会喜欢一天的第一刻。 And I'll assume you want to frame the date as UTC rather than a time zone. 我假设您要将日期设置为UTC而不是时区。 We must go through a OffsetDateTime object to add the time-of-day and offset. 我们必须通过一个OffsetDateTime对象来添加时间和偏移量。 For the offset, we use the constant ZoneOffset.UTC . 对于偏移量,我们使用常量ZoneOffset.UTC Then we extract the more basic Instant class object to convert to a java.util.Date . 然后,我们提取更基本的Instant类对象以转换为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.

Going the other direction: 往另一个方向:

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

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用与JDBC 4.2或更高版本兼容的JDBC驱动程序 No need for strings, no need for java.sql.* classes. 不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes? 在哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

使用days*86400000L进行long计算,否则int值将溢出。

Try this one in your code: 在您的代码中尝试以下代码:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM