問(wèn)題描述
我有一堂課電影其中我有一個(gè)開(kāi)始日期、一個(gè)持續(xù)時(shí)間和一個(gè)停止日期.開(kāi)始和停止日期是日期對(duì)象(私有日期 startDate ...)(這是一個(gè)任務(wù),所以我不能改變它)現(xiàn)在我想通過(guò)將持續(xù)時(shí)間(以分鐘為單位)添加到 startDate 來(lái)自動(dòng)計(jì)算 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.
據(jù)我所知,不推薦使用 Date 的時(shí)間操縱功能,因此這是不好的做法,但另一方面,我看不到將 Date 對(duì)象轉(zhuǎn)換為日歷對(duì)象以操縱時(shí)間并將其重新轉(zhuǎn)換為 Date 對(duì)象的方法.有辦法嗎?如果有什么是最佳做法
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
推薦答案
你可以做的是創(chuàng)建一個(gè) GregorianCalendar
的實(shí)例,然后將 Date
設(shè)置為開(kāi)始時(shí)間:
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;
}
通過(guò)這種方式,您可以訪問(wèn)開(kāi)始時(shí)間并獲取從開(kāi)始到停止的持續(xù)時(shí)間.當(dāng)然,精度取決于您.
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.
這篇關(guān)于日歷的日期對(duì)象 [Java]的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!