views:

145

answers:

5

Hello World,

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

Thanks in advance

Samuel

A: 

Calendar.setTime()

It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

Michael Borgwardt
+1  A: 
Calendar tCalendar = new GregorianCalendar();
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).

Bozhidar Batsov
A: 

You don't need to convert to Calendar for this, you can just use getTime()/setTime() instead.

getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

setTime(long time) : Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. )

There are 1000 milliseconds in a second, and 60 seconds in a minute. Just do the math.

    Date now = new Date();
    Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
    System.out.println(now);
    System.out.println(oneMinuteInFuture);

The L suffix in 1000 signifies that it's a long literal; these calculations usually overflows int easily.

polygenelubricants
+1  A: 

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 startNanos;   //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.startNanos = System.nanoTime();

public void setEndTime() {
        this.duration = System.nanoTime() - this.startNanos;
}

public Calendar getStartTime() {
        return this.startTime;
}

public long getDuratin() {
        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.

Lars Andren
A: 

something like

movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);
Xorty