How do I store time in a variable?
Solution 1
When a date is stored as milliseconds since the epoch, you should use a long
.
There's no need for a double
, since you're not interested in fractions of a millisecond.
You can't use an int
because the maximum int value is only large enough to represent approximately one month in millis.
You can get such a value like this:
long millisSinceEpoch = Calendar.getInstance().getTimeInMillis();
Solution 2
Store the milliseconds in a long
.
You can use the DateTime
class in Joda Time to perform all sorts of intricacies on the resulting number. This overload allows you to plug the milliseconds value directly into a DateTime
object.
Force444
Updated on June 04, 2022Comments
-
Force444 almost 2 years
One of my classes
Event
will have an instance field which is calledtimeStamp
. Now, I have another class which will set thetimeStamp
according to some other algorithm which is not really relevant here.My question is what type should I store this
timeStamp
in? From what I've researched so far I have the impression that it should be calculated in milliseconds and thus store it in adouble
perhaps.Basically the
Clock
class I have simulates time in the following format : hh:mm:ss. However, since it's a discrete event simulation that I'm developing it jumps from event to event, which it determines bytimeStamp
value i.e. each event object has atimeStamp
value which is stored in aPrioityQueue
. So I thought about storing thetimeStamp
in the same format as theClock
, which I guess would involve me creating a new classTimeStamp
that then becomes the type of thetimestamp
. Or should I just make the clock simulate time in milliseconds?What are your thoughts on this? I'm not sure on the most efficient/clean way to implement this.
-
Aquarius Power about 8 yearsand we can avoid floating comparison imprecision!