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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:06:59  来源:igfitidea点击:

how to calculate a minutes from the TimeStamp in java?

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

Timestampis a java.util.Datewith 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.

  1. Parse that string using SimpleDateFormat's parse()method
  2. get the time in long from your Dateobject using getTime()
  3. Take a difference of System.currentTimeMillis()and the long received from getTime()
  4. Divide that by 1000 and then 60
  1. 使用SimpleDateFormatparse()方法解析该字符串
  2. 从您获得长期的时间Date使用对象getTime()
  3. 采取不同的System.currentTimeMillis()和长期收到的getTime()
  4. 将其除以 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*60to convert the milliseconds to minutes

您可以使用Timestamp.getTime()以毫秒为单位获取时间。System.currentTimeMillis()将在当前时间为您提供相同的内容。减去它们并除以1000*60将毫秒转换为分钟