java 如何从java中的TimeStamp计算分钟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4162401/
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 to calculate a minutes from the TimeStamp in java?
提问by GuruKulki
I want to calculate the number of minutes from the TimeStamp. How to do that? for exmple
我想从时间戳计算分钟数。怎么做?例如
I have a TimeStamp value as 13/11/10 1:01 PM. I need to get that in minutes since the current time?
我的时间戳值为 13/11/10 1:01 PM。我需要从当前时间开始在几分钟内得到它?
Hope I am clear THanks
希望我很清楚谢谢
回答by Jon Skeet
Timestamp
is a java.util.Date
with a bit more precision - so assuming you don't care too much about the nanos, just call getTime()
on it to get the millis since the epoch:
Timestamp
是一个java.util.Date
更精确的 - 所以假设你不太关心纳米,只需调用getTime()
它来获取自纪元以来的毫秒:
long now = System.currentTimeMillis(); // See note below
long then = timestamp.getTime();
// Positive if 'now' is later than 'then',
// negative if 'then' is later than 'now'
long minutes = TimeUnit.MILLISECONDS.toMinutes(now - then);
Note that for testability, I personally wouldn'tuse System.currentTimeMillis
- I'd have an interface (e.g. Clock
) representing a "current time service", and inject that. You can then easily have a fake clock.
请注意,为了可测试性,我个人不会使用System.currentTimeMillis
- 我有一个接口(例如Clock
)代表“当前时间服务”,并注入它。然后,您可以轻松拥有一个假时钟。
EDIT: I've assumed you've already got a parsed value. If you haven't, and only have a string, you'll need to parse it first. I'd personally recommend Joda Timeas a rather better date and time API than the built-in stuff, unless you have a particular reason not to use it.
编辑:我假设你已经得到了一个解析值。如果没有,并且只有一个字符串,则需要先解析它。我个人推荐Joda Time作为比内置内容更好的日期和时间 API,除非您有特别的理由不使用它。
回答by Adeel Ansari
Assuming the value is in String
.
假设值在String
.
- Parse that string using
SimpleDateFormat
'sparse()
method - get the time in long from your
Date
object usinggetTime()
- Take a difference of
System.currentTimeMillis()
and the long received fromgetTime()
- Divide that by 1000 and then 60
- 使用
SimpleDateFormat
的parse()
方法解析该字符串 - 从您获得长期的时间
Date
使用对象getTime()
- 采取不同的
System.currentTimeMillis()
和长期收到的getTime()
- 将其除以 1000,然后除以 60
Assuming the value is in Timestamp
, skip step 1 and 2. And notice sin Timestamp is in lowercase.
假设该值在Timestamp
,跳过步骤1和2,并注意小号在时间小号夯实是小写字母。
回答by Michael Mrozek
You can use Timestamp.getTime()
to get the time in milliseconds. System.currentTimeMillis()
will give you the same thing for the current time. Subtract them and divide by 1000*60
to convert the milliseconds to minutes
您可以使用Timestamp.getTime()
以毫秒为单位获取时间。System.currentTimeMillis()
将在当前时间为您提供相同的内容。减去它们并除以1000*60
将毫秒转换为分钟