日期对象到日历[Java] [英] Date object to Calendar [Java]
问题描述
我有一个类电影
在它我有一个开始日期,持续时间和停止日期。
开始和结束日期是日期对象(私人日期startDate ...)
(这是一个分配,所以我不能改变)
现在我想自动计算stopDate通过添加持续时间在min)到startDate。
根据我的知识使用时间操作函数的Date被弃用,因此不好的做法,但另一方面,我看不到转换Date对象到日历对象,以便操作时间,并将其重新转换为Date对象。
有办法吗?
如果有最好的做法
提前感谢
Samuel
你可以做的是创建一个 GregorianCalendar
的实例,然后设置日期
作为开始时间:
日期日期;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);但是,另一种方法是不使用 Date
>。您可以使用这样的方法: private Calendar startTime;
私人长期;
private long startNanos; // Nano-second precision,may be less accurate
...
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;
}
以这种方式,您可以访问开始时间,停止。精确度当然取决于您。
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
Thanks in advance
Samuel
解决方案 What you could do is creating an instance of a GregorianCalendar
and then set the Date
as a start time:
Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
However, another approach is to not use Date
at all. 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.
这篇关于日期对象到日历[Java]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!