[英]Date object to Calendar [Java]
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.根据我的知识,不推荐使用 Date 的时间操作函数,因此是不好的做法,但另一方面,我认为无法将 Date 对象转换为日历对象以操纵时间并将其重新转换为 Date 对象。 Is there a way?
有办法吗? And if there is what would be best practice
如果有什么是最佳实践
What you could do is creating an instance of a GregorianCalendar
and then set the Date
as a start time:您可以做的是创建一个
GregorianCalendar
的实例,然后将Date
设置为开始时间:
Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
However, another approach is to not use Date
at all.但是,另一种方法是根本不使用
Date
。 You could use an approach like this:你可以使用这样的方法:
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.
当然,精度取决于您。
Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);
date is a java.util.Date object.日期是一个 java.util.Date 对象。 You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).
您也可以使用 Calendar.getInstance() 来获取 Calendar 实例(效率更高)。
查看 API 方法的签名和描述通常很有用,而不仅仅是它们的名称 :) - 即使在 Java 标准 API 中,名称有时也会产生误导。
You don't need to convert to Calendar
for 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.getTime()
:返回自 1970 年 1 月 1 日格林威治标准时间 00:00:00 以来由此 Date 对象表示的毫秒数。
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.setTime(long time)
:将此 Date 对象设置为表示一个时间点,即 1970 年 1 月 1 日 00:00:00 GMT 之后的时间毫秒。 ))
There are 1000 milliseconds in a second, and 60 seconds in a minute.一秒有 1000 毫秒,一分钟有 60 秒。 Just do the math.
只是做数学。
Date now = new Date();
Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
System.out.println(now);
System.out.println(oneMinuteInFuture);
The L
suffix in 1000
signifies that it's a long
literal; 1000
的L
后缀表示它是一个long
字面量; these calculations usually overflows int
easily.这些计算通常很容易溢出
int
。
Instant stop =
myUtilDateStart.toInstant()
.plus( Duration.ofMinutes( x ) )
;
Other Answers are correct, especially the Answer by Borgwardt .其他答案是正确的,尤其是Borgwardt 的答案。 But those Answers use outmoded legacy classes.
但是这些答案使用过时的遗留类。
The original date-time classes bundled with Java have been supplanted with java.time classes.与 Java 捆绑的原始日期时间类已被 java.time 类取代。 Perform your business logic in java.time types.
在 java.time 类型中执行您的业务逻辑。 Convert to the old types only where needed to work with old code not yet updated to handle java.time types.
仅在需要处理尚未更新以处理 java.time 类型的旧代码时才转换为旧类型。
If your Calendar
is actually a GregorianCalendar
you can convert to a ZonedDateTime
.如果您的
Calendar
实际上是GregorianCalendar
您可以转换为ZonedDateTime
。 Find new methods added to the old classes to facilitate conversion to/from java.time types.查找添加到旧类中的新方法,以方便与 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 Calendar
is not a Gregorian
, call toInstant
to get an Instant
object.如果您的
Calendar
不是Gregorian
,请调用toInstant
以获取Instant
对象。 TheInstant
class represents a moment on the timeline in UTC with a resolution of nanoseconds . Instant
类表示UTC时间轴上的一个时刻,分辨率为纳秒。
Instant instant = myCal.toInstant();
Similarly, if starting with a java.util.Date
object, convert to an Instant
.同样,如果从
java.util.Date
对象开始,则转换为Instant
。 TheInstant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). 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.Date
object, 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 Answer to another Question.有关在遗留日期时间类型和 java.time 之间转换的更多讨论以及漂亮的图表,请参阅我对另一个问题的回答。
Duration
Represent the span of time as a Duration
object.将时间跨度表示为
Duration
对象。 Your input for the duration is a number of minutes as mentioned in the Question.您输入的持续时间是问题中提到的分钟数。
Duration d = Duration.ofMinutes( yourMinutesGoHere );
You can add that to the start to determine the stop.您可以将其添加到开始以确定停止。
Instant stop = startInstant.plus( d );
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.Date
, Calendar
,和SimpleDateFormat
。
The Joda-Time project, now in maintenance mode , advises migration to java.time.现在处于维护模式的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 。
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 .您可以在这里找到一些有用的类,比如
Interval
, YearWeek
, YearQuarter
,和更多。
就像是
movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);
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);
Extension for converting date to calendar in Kotlin.在 Kotlin 中将日期转换为日历的扩展。
fun Date?.toCalendar(): Calendar? {
return this?.let { date ->
val calendar = Calendar.getInstance()
calendar.time = date
calendar
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.