日历对象的日期对象 [Java]

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

Date object to Calendar [Java]

javadatecalendar

提问by Samuel

I have a class Movie in it i have a start Date, a duration and a stop Date. Start and stop Date are Date Objects (private Date startDate ...) (It's an assignment so i cant change that) now I want to automatically calculate the stopDate by adding the duration (in min) to the startDate.

我有一个电影类,我有一个开始日期、一个持续时间和一个停止日期。开始和停止日期是日期对象(私人日期开始日期...)(这是一个分配,所以我不能改变它)现在我想通过将持续时间(以分钟为单位)添加到开始日期来自动计算停止日期。

By my knowledge working with the time manipulating functions of Date is deprecated hence bad practice but on the other side i see no way to convert the Date object to a calendar object in order to manipulate the time and reconvert it to a Date object. Is there a way? And if there is what would be best practice

据我所知,使用 Date 的时间操作函数已被弃用,因此是不好的做法,但另一方面,我认为无法将 Date 对象转换为日历对象以操纵时间并将其重新转换为 Date 对象。有办法吗?如果有什么是最佳实践

采纳答案by Lars Andren

What you could do is creating an instance of a GregorianCalendarand then set the Dateas a start time:

您可以做的是创建 a 的实例,GregorianCalendar然后将其设置Date为开始时间:

Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);

However, another approach is to not use Dateat all. You could use an approach like this:

但是,另一种方法是根本不使用Date。你可以使用这样的方法:

private Calendar startTime;
private long duration;
private long startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuration() {
        return this.duration;
}

In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

通过这种方式,您可以访问开始时间并获取从开始到停止的持续时间。当然,精度取决于您。

回答by Michael Borgwardt

Calendar.setTime()

Calendar.setTime()

It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

查看 API 方法的签名和描述通常很有用,而不仅仅是它们的名称 :) - 即使在 Java 标准 API 中,名称有时也会产生误导。

回答by Bozhidar Batsov

Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);

date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).

日期是一个 java.util.Date 对象。您也可以使用 Calendar.getInstance() 来获取 Calendar 实例(效率更高)。

回答by polygenelubricants

You don't need to convert to Calendarfor this, you can just use getTime()/setTime()instead.

您不需要为此转换Calendar为,您可以使用getTime()/setTime()代替。

getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

setTime(long time): Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. )

getTime():返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来的毫秒数,由此 Date 对象表示。

setTime(long time):设置此 Date 对象以表示时间点,即 1970 年 1 月 1 日 00:00:00 GMT 之后的时间毫秒。)

There are 1000 milliseconds in a second, and 60 seconds in a minute. Just do the math.

一秒有 1000 毫秒,一分钟有 60 秒。只是做数学。

    Date now = new Date();
    Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
    System.out.println(now);
    System.out.println(oneMinuteInFuture);

The Lsuffix in 1000signifies that it's a longliteral; these calculations usually overflows inteasily.

L在后缀1000意味着这是一个long文字; 这些计算通常int很容易溢出。

回答by Xorty

something like

就像是

movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);

回答by Basil Bourque

tl;dr

tl;博士

Instant stop = 
    myUtilDateStart.toInstant()
                   .plus( Duration.ofMinutes( x ) ) 
;

java.time

时间

Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.

其他答案是正确的,尤其是Borgwardt 的答案。但是这些答案使用过时的遗留类。

The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.

与 Java 捆绑的原始日期时间类已被 java.time 类取代。在 java.time 类型中执行您的业务逻辑。仅在需要处理尚未更新以处理 java.time 类型的旧代码时才转换为旧类型。

If your Calendaris actually a GregorianCalendaryou can convert to a ZonedDateTime. Find new methods added to the old classes to facilitate conversion to/from java.time types.

如果您Calendar实际上是 a 则GregorianCalendar可以转换为ZonedDateTime. 查找添加到旧类中的新方法,以方便与 java.time 类型之间的转换。

if( myUtilCalendar instanceof GregorianCalendar ) {
    GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
    ZonedDateTime zdt = gregCal.toZonedDateTime();  // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if 

If your Calendaris not a Gregorian, call toInstantto get an Instantobject. The Instantclass represents a moment on the timeline in UTCwith a resolution of nanoseconds.

如果您Calendar不是Gregorian,请调用toInstant以获取Instant对象。该Instant级表示时间轴上的时刻UTC,分辨率为纳秒

Instant instant = myCal.toInstant();

Similarly, if starting with a java.util.Dateobject, convert to an Instant. The Instantclass represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).

同样,如果以java.util.Date对象开头,则转换为Instant. 该Instant级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。

Instant instant = myUtilDate.toInstant();

Apply a time zone to get a ZonedDateTime.

应用时区以获取ZonedDateTime.

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

To get a java.util.Dateobject, go through the Instant.

要获取java.util.Date对象,请通过Instant.

java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );

For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answerto another Question.

有关在遗留日期时间类型和 java.time 之间转换的更多讨论以及漂亮的图表,请参阅对另一个问题的回答

Duration

Duration

Represent the span of time as a Durationobject. Your input for the duration is a number of minutes as mentioned in the Question.

将时间跨度表示为Duration对象。您输入的持续时间是问题中提到的分钟数。

Duration d = Duration.ofMinutes( yourMinutesGoHere );

You can add that to the start to determine the stop.

您可以将其添加到开始以确定停止。

Instant stop = startInstant.plus( d ); 


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

现在处于维护模式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

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 Vitor Reais

Here is a full example on how to transform your date in different types:

以下是关于如何将日期转换为不同类型的完整示例:

Date date = Calendar.getInstance().getTime();

    // Display a date in day, month, year format
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with day name in a short format
    formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Display date with a short day and month name
    formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
    today = formatter.format(date);
    System.out.println("Today : " + today);

    // Formatting date with full day and month name and show time up to
    // milliseconds with AM/PM
    formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    today = formatter.format(date);
    System.out.println("Today : " + today);