How do I store time in a variable?

12,322

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.

Share:
12,322
Force444
Author by

Force444

Updated on June 04, 2022

Comments

  • Force444
    Force444 almost 2 years

    One of my classes Event will have an instance field which is called timeStamp. Now, I have another class which will set the timeStamp 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 a double 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 by timeStamp value i.e. each event object has a timeStamp value which is stored in a PrioityQueue. So I thought about storing the timeStamp in the same format as the Clock , which I guess would involve me creating a new class TimeStamp that then becomes the type of the timestamp. 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
    Aquarius Power about 8 years
    and we can avoid floating comparison imprecision!