开发者

how to calculate a minutes from the TimeStamp in java?

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?

Hope I am clear THanks


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:

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't use 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.

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 Time as a rather better date and time API than the built-in stuff, unless you have a particular reason not to use it.


Assuming the value is in String.

  1. Parse that string using SimpleDateFormat's parse() method
  2. get the time in long from your Date object using getTime()
  3. Take a difference of System.currentTimeMillis() and the long received from getTime()
  4. Divide that by 1000 and then 60

Assuming the value is in Timestamp, skip step 1 and 2. And notice s in Timestamp is in lowercase.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜