問題描述
我有一堂課電影其中我有一個開始日期、一個持續時間和一個停止日期.開始和停止日期是日期對象(私有日期 startDate ...)(這是一個任務,所以我不能改變它)現在我想通過將持續時間(以分鐘為單位)添加到 startDate 來自動計算 stopDate.
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.
據我所知,不推薦使用 Date 的時間操縱功能,因此這是不好的做法,但另一方面,我看不到將 Date 對象轉換為日歷對象以操縱時間并將其重新轉換為 Date 對象的方法.有辦法嗎?如果有什么是最佳做法
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
推薦答案
你可以做的是創建一個 GregorianCalendar
的實例,然后將 Date
設置為開始時間:
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);
但是,另一種方法是根本不使用 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]的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!