日历的日期对象 [Java]

Date object to Calendar [Java](日历的日期对象 [Java])
本文介绍了日历的日期对象 [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.

这篇关于日历的日期对象 [Java]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Month is not printed from a date - Java DateFormat(月份不是从日期打印的 - Java DateFormat)
java get week of year for given a date(java获取给定日期的一年中的一周)
Get the number of days, weeks, and months, since Epoch in Java(获取自 Java 中的 Epoch 以来的天数、周数和月数)
Is there a good way to get the date of the coming Wednesday?(有什么好方法可以得到即将到来的星期三的日期吗?)
Calendar view for Android GingerBread and before (APIlt;11)(Android GingerBread 及之前的日历视图 (API11))
How to save and retrieve Date in SharedPreferences(如何在 SharedPreferences 中保存和检索日期)