Search code examples
javadatetimetimemilliseconds

How do I store time in a variable?


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.


Solution

  • 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();