Reputation: 18586
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
Upvotes: 69
Views: 107910
Reputation: 401
Extension for converting date to calendar in Kotlin.
fun Date?.toCalendar(): Calendar? {
return this?.let { date ->
val calendar = Calendar.getInstance()
calendar.time = date
calendar
}
}
Upvotes: 1
Reputation: 31
Here is a full example on how to transform your date in different types:
Date date = Calendar.getInstance().getTime();
// Display a date in day, month, year format
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with day name in a short format
formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with a short day and month name
formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Formatting date with full day and month name and show time up to
// milliseconds with AM/PM
formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
today = formatter.format(date);
System.out.println("Today : " + today);
Upvotes: 0
Reputation: 340070
Instant stop =
myUtilDateStart.toInstant()
.plus( Duration.ofMinutes( x ) )
;
Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.
The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.
If your Calendar
is actually a GregorianCalendar
you can convert to a ZonedDateTime
. Find new methods added to the old classes to facilitate conversion to/from java.time types.
if( myUtilCalendar instanceof GregorianCalendar ) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
ZonedDateTime zdt = gregCal.toZonedDateTime(); // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if
If your Calendar
is not a Gregorian
, call toInstant
to get an Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myCal.toInstant();
Similarly, if starting with a java.util.Date
object, convert to an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
Apply a time zone to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
To get a java.util.Date
object, go through the Instant
.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );
For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.
Duration
Represent the span of time as a Duration
object. Your input for the duration is a number of minutes as mentioned in the Question.
Duration d = Duration.ofMinutes( yourMinutesGoHere );
You can add that to the start to determine the stop.
Instant stop = startInstant.plus( d );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Upvotes: 2
Reputation: 8781
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.
Upvotes: 101
Reputation: 56665
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).
Upvotes: 29
Reputation: 18861
something like
movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);
Upvotes: 0
Reputation: 383986
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.
Upvotes: 6
Reputation: 346476
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.
Upvotes: 6