Java 如何在日期中添加一天?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1005523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:10:14  来源:igfitidea点击:

How to add one day to a date?

javadatetime

提问by user93796

I want to add one day to a particular date. How can I do that?

我想在特定日期添加一天。我怎样才能做到这一点?

Date dt = new Date();

Now I want to add one day to this date.

现在我想在这个日期上加一天。

采纳答案by Daniel Rikowski

Given a Date dtyou have several possibilities:

鉴于 aDate dt你有几种可能性:

Solution 1:You can use the Calendarclass for that:

解决方案 1:您可以使用Calendar该类:

Date dt = new Date();
Calendar c = Calendar.getInstance(); 
c.setTime(dt); 
c.add(Calendar.DATE, 1);
dt = c.getTime();

Solution 2:You should seriously consider using the Joda-Time library, because of the various shortcomings of the Dateclass. With Joda-Time you can do the following:

解决方案2:你应该认真考虑使用Joda-Time库,因为类的各种缺点Date。使用 Joda-Time,您可以执行以下操作:

Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);

Solution 3:With Java 8you can also use the new JSR 310API (which is inspired by Joda-Time):

解决方案 3:使用Java 8,您还可以使用新的JSR 310API(受 Joda-Time 启发):

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

回答by Bruce ONeel

To make it a touch less java specific, the basic principle would be to convert to some linear date format, julian days, modified julian days, seconds since some epoch, etc, add your day, and convert back.

为了使它与 Java 无关,基本原则是转换为某种线性日期格式、儒略日、修改后的儒略日、自某个纪元以来的秒数等,添加您的日期,然后再转换回来。

The reason for doing this is that you farm out the "get the leap day, leap second, etc right' problem to someone who has, with some luck, not mucked this problem up.

这样做的原因是,您可以将“获得闰日、闰秒等正确”的问题交给那些幸运地没有把这个问题搞砸的人。

I will caution you that getting these conversion routines right can be difficult. There are an amazing number of different ways that people mess up time, the most recent high profile example was MS's Zune. Dont' poke too much fun at MS though, it's easy to mess up. It doesn't help that there are multiple different time formats, say, TAI vs TT.

我会提醒您,正确使用这些转换例程可能很困难。人们打乱时间的方式有很多种,最近最引人注目的例子是 MS 的 Zune。不过不要拿 MS 开玩笑,这很容易搞砸。有多种不同的时间格式,例如 TAI 与 TT,这无济于事。

回答by Mnementh

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.

Date 有一个使用自 UNIX 时代以来的毫秒数的构造函数。getTime() 方法为您提供了该值。所以增加一天的毫秒数,就可以了。如果您想定期进行此类操作,我建议为这些值定义常量。

Important hint: That is not correct in all cases. Read the WARNING comment, below.

重要提示:并非在所有情况下都是正确的。阅读下面的警告评论。

回答by Vinay Pandey

use DateTime object obj.Add to add what ever you want day hour and etc. Hope this works:)

使用 DateTime 对象 obj.Add 添加你想要的时间等。希望这有效:)

回答by navneet

This will increase any date by exactly one

这将使任何日期增加一

String untildate="2011-10-08";//can take any date in current format    
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );   
Calendar cal = Calendar.getInstance();    
cal.setTime( dateFormat.parse(untildate));    
cal.add( Calendar.DATE, 1 );    
String convertedDate=dateFormat.format(cal.getTime());    
System.out.println("Date increase by one.."+convertedDate);

回答by remipod

I prefer jodafor date and time arithmetics because it is much better readable:

我更喜欢joda用于日期和时间算术,因为它的可读性要好得多:

Date tomorrow = now().plusDays(1).toDate();

Or

或者

endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()

回答by Basil Bourque

tl;dr

tl;博士

LocalDate.of( 2017 , Month.JANUARY , 23 ) 
         .plusDays( 1 )

java.time

时间

Best to avoid the java.util.Dateclass altogether. But if you must do so, you can convert between the troublesome old legacy date-time classes and the modern java.time classes. Look to new methods added to the old classes.

最好java.util.Date完全避免上课。但是,如果您必须这样做,您可以在麻烦的旧日期时间类和现代 java.time 类之间进行转换。寻找添加到旧类中的新方法。

Instant

Instant

The Instantclass, is close to being equivalent to Date, both being a moment on the timeline. Instantresolves to nanoseconds, while Dateis milliseconds.

Instant级,接近等同于Date,两者都是在时间轴上一会儿。Instant解析为纳秒,Date而是毫秒。

Instant instant = myUtilDate.toInstant() ;

You could add a day to this, but keep in mind this in UTC. So you will not be accounting for anomalies such as Daylight Saving Time. Specify the unit of time with the ChronoUnitclass.

您可以为此添加一天,但请记住这是 UTC。因此,您不会考虑夏令时等异常情况。用ChronoUnit类指定时间单位。

Instant nextDay = instant.plus( 1 , ChronoUnit.DAYS ) ;

ZonedDateTime

ZonedDateTime

If you want to be savvy with time zones, specify a ZoneIdto get a ZonedDateTime. Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

如果您想精通时区,请指定 aZoneId以获取ZonedDateTime. 以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
ZonedDateTime zdtNextDay = zdt.plusDays( 1 ) ;

You can also represent your span-of-time to be added, the one day, as a Period.

您还可以将要添加的时间跨度(一天)表示为Period.

Period p = Period.ofDays( 1 ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ).plus( p ) ;

You may want the first moment of that next day. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time, such as 01:00:00. Let java.timedetermine the first moment of the day on that date in that zone.

你可能想要第二天的第一刻。不要假设一天从 00:00:00 开始。夏令时 (DST) 等异常情况意味着一天可能在其他时间开始,例如 01:00:00。让java.time确定该区域中该日期当天的第一时刻。

LocalDate today = LocalDate.now( z ) ;
LocalDate tomorrow = today.plus( p ) ;
ZonedDateTime zdt = tomorrow.atStartOfDay( z ) ;


About java.time

关于java.time

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

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject 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.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多



Update:The Joda-Time library is now in maintenance mode. The team advises migration to the java.time classes. I am leaving this section intact for history.

更新:Joda-Time 库现在处于维护模式。该团队建议迁移到 java.time 类。为了历史,我将这部分原封不动地保留下来。

Joda-Time

乔达时间

The Joda-Time2.3 library makes this kind of date-time work much easier. The java.util.Date class bundled with Java is notoriously troublesome, and should be avoided.

乔达时间2.3库使这种日期时间的工作变得更加容易。与 Java 捆绑在一起的 java.util.Date 类是出了名的麻烦,应该避免。

Here is some example code.

这是一些示例代码。

Your java.util.Date is converted to a Joda-Time DateTimeobject. Unlike a j.u.Date, a DateTime truly knows its assigned time zone. Time zone is crucial as adding a day to get the same wall-clock timetomorrow might mean making adjustments such as for a 23-hour or 25-hour day in the case of Daylight Saving Time (DST)here in the United States. If you specify the time zone, Joda-Time can make that kind of adjustment. After adding a day, we convert the DateTime object back into a java.util.Date object.

您的 java.util.Date 被转换为 Joda-Time DateTime对象。与 juDate 不同,DateTime 真正知道其指定的时区。时区至关重要,因为添加一天以获得明天相同的挂钟时间可能意味着进行调整,例如在美国的夏令时 (DST)的情况下,调整为 23 小时或 25 小时。如果您指定时区,Joda-Time 可以进行这种调整。添加一天后,我们将 DateTime 对象转换回 java.util.Date 对象。

java.util.Date yourDate = new java.util.Date();

// Generally better to specify your time zone rather than rely on default.
org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
DateTime now = new DateTime( yourDate, timeZone );
DateTime tomorrow = now.plusDays( 1 );
java.util.Date tomorrowAsJUDate = tomorrow.toDate();

Dump to console…

转储到控制台...

System.out.println( "yourDate: " + yourDate );
System.out.println( "now: " + now );
System.out.println( "tomorrow: " + tomorrow );
System.out.println( "tomorrowAsJUDate: " + tomorrowAsJUDate );

When run…

运行时…

yourDate: Thu Apr 10 22:57:21 PDT 2014
now: 2014-04-10T22:57:21.535-07:00
tomorrow: 2014-04-11T22:57:21.535-07:00
tomorrowAsJUDate: Fri Apr 11 22:57:21 PDT 2014

回答by behzad

As mentioned in the Top answer, since java 8 it is possible to do:

正如 Top answer 中提到的,由于 java 8 可以执行以下操作:

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

but this can sometimes lead to an DateTimeExceptionlike this:

但这有时会导致DateTimeException这样的:

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant

It is possible to avoid this Exception by simply passing the time zone:

可以通过简单地传递时区来避免此异常:

LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);

回答by Burak

In very special case If you asked to do your own date class, possibly from your Computer Programming Professor; This method would do very fine job.

在非常特殊的情况下 这种方法会做得很好。

public void addOneDay(){
    int [] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    day++;
    if (day> months[month-1]){
        month++;
        day = 1;
        if (month > 12){
            year++;
            month = 1;
        }
    }
}

回答by nazar_art

Java 1.8 versionhas nice update for data time API.

Java 1.8 版本对数据时间 API 进行了很好的更新。

Here is snippet of code:

这是代码片段:

    LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
    System.out.println("last april day: " + lastAprilDay);
    LocalDate firstMay = lastAprilDay.plusDays(1);
    System.out.println("should be first may day: " + firstMay);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
    String formatDate = formatter.format(firstMay);
    System.out.println("formatted date: " + formatDate);

Output:

输出:

last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01

For more info see Java documentations to this classes:

有关更多信息,请参阅此类的 Java 文档: