Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date object to Calendar [Java]

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

like image 526
Samuel Avatar asked Apr 28 '10 08:04

Samuel


People also ask

How do you convert a calendar to date and vice versa in Java?

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.


2 Answers

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.

like image 141
Lars Andren Avatar answered Sep 26 '22 01:09

Lars Andren


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).

like image 44
Bozhidar Batsov Avatar answered Sep 22 '22 01:09

Bozhidar Batsov