user1809095
user1809095

Reputation: 411

Java How to get millisecond part of current time and not from 1970

I am using System.currentTimeMillis() to get number of milliseconds since 1970, I can get current Hour, Minute and seconds using following:

Long currTimeInMilliSec =   System.currentTimeMillis()
int h = (((currTimeInMilliSec / 1000) / 3600 ) % 24)
int m = (((currTimeInMilliSec / 1000) / 60) % 60)
int s = ((currTimeInMilliSec / 1000) % 60)

How can I calculate millisecond of Current time (not from 1970), because if I use int ms = currentTimeInMilliSec that would be number of milliseconds since 1970.

Note: For some reason, I need to use only currentTimeMillis function to calculate and I don't want to use other functions or external libraries.

Upvotes: 2

Views: 1166

Answers (2)

Mike Nakis
Mike Nakis

Reputation: 62159

Use currentTimeInMilliSec % 1000.

You can also think about it this way: it works for the same reason that int m = totalMinutes % 60 works, and you have already found that this works.

But a more detailed explanation is as follows: N % M gives you a number from 0 to M - 1. So, you will always get a number of milliseconds from 0 to 999. And each time your currentTimeInMilliSec advances by one, this number also advances by one, but if this number ever exceeds 999, it warps around to 0, which is the exact behaviour that you want.

Upvotes: 2

user1803551
user1803551

Reputation: 13427

This question is about arithmetics and not programming, but here:

Given a specific time t, the number of ms from t to current time is:

System.currentTimeMillis() + ([midnight, January 1, 1970 UTC] - t).

Now all you have to do is decide on a unit of measurement and convert all the abstractly represented times aboves to it and perform the calculation.

Example:

If t is midnight, January 1, 1960 UTC, then

[midnight, January 1, 1970 UTC] - t = [number of ms in 10 years]

and the number of ms from t to now is

System.currentTimeMillis() + [number of ms in 10 years].

Upvotes: 0

Related Questions