日历的日期对象 [Java]

2022-01-11 00:00:00 date calendar java

我有一堂课电影其中我有一个开始日期、一个持续时间和一个停止日期.开始和停止日期是日期对象(私有日期 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.

相关文章