Search code examples
javatimemilliseconds

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.


Solution

  • 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.