java 如何在变量中存储时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13261388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I store time in a variable?
提问by DSF
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.
我的一个类Event
将有一个实例字段,称为timeStamp
. 现在,我有另一个类,它将timeStamp
根据一些其他的算法来设置,这在这里并不真正相关。
My question is what typeshould 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.
我的问题是我应该将它存储在什么类型timeStamp
中?从我到目前为止的研究来看,我的印象是它应该以毫秒为单位计算,因此将它存储在一个double
可能的。
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?
基本上,Clock
我的课程以以下格式模拟时间:hh:mm:ss。然而,由于我正在开发它是一个离散事件模拟,它从一个事件跳到另一个事件,它由timeStamp
值决定,即每个事件对象都有一个timeStamp
存储在PrioityQueue
. 因此,我认为有关存储timeStamp
在相同的格式Clock
,我猜会涉及我创建一个新类TimeStamp
是则成为的类型timestamp
。或者我应该让时钟以毫秒为单位模拟时间?
What are your thoughts on this? I'm not sure on the most efficient/clean way to implement this.
你对此有何看法?我不确定实现这一点的最有效/最干净的方法。
采纳答案by jahroy
When a date is stored as milliseconds since the epoch, you should use a long
.
当日期存储为自纪元以来的毫秒数时,您应该使用long
.
There's no need for a double
, since you're not interested in fractions of a millisecond.
不需要 a double
,因为您对几分之一毫秒不感兴趣。
You can't use an int
because the maximum int value is only large enough to represent approximately one month in millis.
您不能使用 an,int
因为最大 int 值仅足以表示大约一个月的毫秒数。
You can get such a value like this:
你可以得到这样的值:
long millisSinceEpoch = Calendar.getInstance().getTimeInMillis();
long millisSinceEpoch = Calendar.getInstance().getTimeInMillis();
回答by Robert Harvey
Store the milliseconds in a long
.
将毫秒存储在long
.
You can use the DateTime
class in Joda Time to perform all sorts of intricacies on the resulting number. This overloadallows you to plug the milliseconds value directly into a DateTime
object.
您可以使用DateTime
Joda Time 中的类对结果数字执行各种复杂的操作。 此重载允许您将毫秒值直接插入DateTime
对象中。