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.
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
Well, you can use the Calendar. setTime() and Calendar. getTime() method to convert the Calendar to Date and vice-versa. The Instance class is the equivalent to java.
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);
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.
Calendar tCalendar = Calendar.getInstance(); tCalendar.setTime(date);
date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With