This question already has an answer here:
I want to have something like this:
public class Stream
{
public startTime;
public endTime;
public getDuration()
{
return startTime - endTime;
}
}
Also it is important that for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.
Which types to use in order to accomplish this in Java?
If you are writing an application that must deal with durations of time, then please take a look at Joda-Time which has class specifically for handling Durations, Intervals, and Periods. Your
getDuration()
method looks like it could return a Joda-Time Interval:If you prefer using Java's Calendar API you can try this,
Java provides the static method
System.currentTimeMillis()
. And that's returning a long value, so it's a good reference. A lot of other classes accept a 'timeInMillis' parameter which is long as well.And a lot of people find it easier to use the Joda Time library to do calculations on dates and times.
If the purpose is to simply print coarse timing information to your program logs, then the easy solution for Java projects is not to write your own stopwatch or timer classes, but just use the
org.apache.commons.lang.time.StopWatch
class that is part of Apache Commons Lang.If you're getting your timestamps from
System.currentTimeMillis()
, then your time variables should be longs.Use this:
the "else" part can get it correct