问题描述
我有一堂课电影其中我有一个开始日期、一个持续时间和一个停止日期.开始和停止日期是日期对象(私有日期 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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)