Java 为日期添加秒数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23548677/
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-13 23:49:16  来源:igfitidea点击:

Adding seconds to a Date

java

提问by Helio Bentzen

I need add a certain time in seconds to my Date. For this, I'm making it:

我需要在我的日期中添加一个以秒为单位的特定时间。为此,我正在这样做:

Date startTime = dayStart(dateSelected);    
startTime.setSeconds(startTime.getSeconds()+30);

But, for this way I get this alerts:

但是,通过这种方式,我收到了以下警报:

Multiple markers at this line

- The method setSeconds(int) from the type Date is deprecated
- The method getSeconds() from the type Date is deprecated

此行有多个标记

- 不推荐使用 Date 类型的 setSeconds(int)
方法 -不推荐使用 Date 类型的 getSeconds()

What's the better way to don't get these deprecated alerts?

不接收这些已弃用警报的更好方法是什么?

采纳答案by Basil Bourque

tl;dr

tl;博士

What's the better way to don't get these deprecated alerts?

不接收这些已弃用警报的更好方法是什么?

Do not use that terrible class, java.util.Date. Use its replacement, Instant.

不要使用那个可怕的类,java.util.Date. 使用它的替代品,Instant

myJavaUtilDate.toInstant().plusSeconds( 30 ) 

java.time

时间

The modern approach uses the java.timeclasses defined in JSR 310 that supplanted the terrible legacy date-time classes such as Calendarand Date.

现代方法使用JSR 310 中定义的java.time类取代了可怕的遗留日期时间类,例如CalendarDate

Table of date-time types in Java, both modern and legacy

Java 中的日期时间类型表,现代和传统

Start of day

一天的开始

Date startTime = dayStart(dateSelected);

日期开始时间 = dayStart(dateSelected);

If you want the first moment of the day, you need a LocalDate(date) and a ZoneId(time zone).

如果你想要一天中的第一刻,你需要一个LocalDate(日期)和一个ZoneId(时区)。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate localDate = LocalDate.now( z ) ;  // Get the current date as seen in a particular time zone.

Get the start of that date. Specify a time zone to get a ZonedDateTime. Always let java.timedetermine the first moment of the day. Some dates in some zones do notstart at 00:00:00. They might start at another time such as 01:00:00.

获取该日期的开始时间。指定时区以获取ZonedDateTime. 始终让java.time确定一天中的第一个时刻。某些区域中的某些日期不是从 00:00:00 开始的。他们可能会在其他时间开始,例如 01:00:00。

ZonedDateTime zdt = localDate.atStartOfDay( z ) ;

Date-time math

日期时间数学

You can perform date-time math by calling the plus…& minus…methods.

您可以通过调用plus…&minus…方法执行日期时间数学运算。

Specify a span-of-time not attached to the timeline using either Durationor Periodclasses.

使用DurationPeriod类指定不附加到时间线的时间跨度。

Duration d = Duration.ofSeconds( 30 ) ;

Add.

添加。

ZonedDateTime zdtLater = zdt.plus( d ) ;

Or combine those 2 lines into 1.

或者将这两行合并为 1。

ZonedDateTime zdtLater = zdt.plusSeconds( 30 ) ;

Converting

转换

If you need to interoperate with old code not yet updated to java.time, call new conversion methods added to the old classes.

如果您需要与尚未更新为java.time 的旧代码进行互操作,请调用添加到旧类中的新转换方法。

The java.util.Datelegacy class represents a moment in UTC with a resolution of milliseconds. Its replacement is java.time.Instant, also a moment in UTC but with a much finer resolution of nanoseconds.

java.util.Date传统类表示UTC一会儿用毫秒的分辨率。它的替代品是java.time.Instant,也是 UTC 中的一个时刻,但具有更精细的纳秒分辨率。

You can extract a Instantfrom a ZonedDateTime, effectively adjusting from some time zone to UTC. Same moment, same point on the timeline, different wall-clock time.

您可以Instant从 a 中提取 a ZonedDateTime,有效地将某个时区调整为 UTC。同一时刻,时间线上的同一点,不同的挂钟时间。

Instant instant = zdtLater.toInstant() ;


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

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

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

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

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,和更多

回答by azurefrog

The methods on Dateare deprecated for good reason.
All of that functionality has been moved to the Calendarclass:

Date不推荐使用的方法有充分的理由。
所有这些功能都已移到Calendar类中:

    Date oldDate = new Date();
    Calendar gcal = new GregorianCalendar();
    gcal.setTime(oldDate);
    gcal.add(Calendar.SECOND, 30);
    Date newDate = gcal.getTime();

回答by Jeff Scott Brown

import java.util.Date;
import java.util.Calendar;

public class DateStuff {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();

        cal.add(Calendar.SECOND, 30);
        Date later = cal.getTime();

        System.out.println("Now: " + now);
        System.out.println("Later: " + later);
    }
}

回答by akhilless

JavaDocfor Date class reads

用于日期类读取的JavaDoc

As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

从 JDK 1.1 开始,应该使用 Calendar 类在日期和时间字段之间进行转换,并且应该使用 DateFormat 类来格式化和解析日期字符串。不推荐使用 Date 中的相应方法。

And setSecondsmethod in JavaDoc has following warning

setSeconds在Javadoc方法如下警告

Deprecated. As of JDK version 1.1, replaced by Calendar.set(Calendar.SECOND, int seconds).

已弃用。从 JDK 1.1 版开始,由 Calendar.set(Calendar.SECOND, int seconds) 取代。

That means you should do something like this

这意味着你应该做这样的事情

int numberOfseconds = 30;
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateSelected);
calendar.add(Calendar.SECOND, numberOfSeconds);