Imam Bux Mallah
Imam Bux Mallah

Reputation: 393

Print milliseconds only (0 to 999)

I have worked a bit on the following code but still unable to print milliseconds (not all the millisecond from epoch time to user defined time). Where am I lacking to print remaining milliseconds e.g. If seconds are 30 exactly, milliseconds should be only 0. Milliseconds should not be more than 999 obviously.

    // Sets current date by default
    Calendar ob = Calendar.getInstance();

    // Sets user defined date with year, month, day of month respectively
    Calendar dob = Calendar.getInstance();
    dob.set(1990, 3, 25);

    // Want to get milliseconds only (0 - 999)
    long milli = dob.getTimeInMillis() - ( 60 * 60 * 24 * 30 * 12 * ( ob.get(Calendar.YEAR) - dob.get(Calendar.YEAR) ) );
    System.out.println(milli);

Upvotes: 0

Views: 513

Answers (3)

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39718

You want what's called the modulus operator, %. This basically finds the remainder of division.

long milli = dob.getTimeInMillis() % 1000;

Upvotes: 1

Chris Gerken
Chris Gerken

Reputation: 16390

Why not do

long justMillis = dob.getTimeInMillis() % 1000;

Upvotes: 3

EasterBunnyBugSmasher
EasterBunnyBugSmasher

Reputation: 1582

System.out.println(milli % 1000);

Upvotes: 0

Related Questions