How can I get the count of milliseconds since midnight for the current?

399,355

Solution 1

Do you mean?

long millis = System.currentTimeMillis() % 1000;

BTW Windows doesn't allow timetravel to 1969

C:\> date
Enter the new date: (dd-mm-yy) 2/8/1969
The system cannot accept the date entered.

Solution 2

Use Calendar

Calendar.getInstance().get(Calendar.MILLISECOND);

or

Calendar c=Calendar.getInstance();
c.setTime(new Date()); /* whatever*/
//c.setTimeZone(...); if necessary
c.get(Calendar.MILLISECOND);

In practise though I think it will nearly always equal System.currentTimeMillis()%1000; unless someone has leap-milliseconds or some calendar is defined with an epoch not on a second-boundary.

Solution 3

Calendar.getInstance().get(Calendar.MILLISECOND);

Solution 4

tl;dr

You ask for the fraction of a second of the current time as a number of milliseconds (not count from epoch).

Instant.now()                               // Get current moment in UTC, then…
       .get( ChronoField.MILLI_OF_SECOND )  // interrogate a `TemporalField`.

2017-04-25T03:01:14.113Z → 113

  1. Get the fractional second in nanoseconds (billions).
  2. Divide by a thousand to truncate to milliseconds (thousands).

See this code run live at IdeOne.com.

Using java.time

The modern way is with the java.time classes.

Capture the current moment in UTC.

Instant.now()

Use the Instant.get method to interrogate for the value of a TemporalField. In our case, the TemporalField we want is ChronoField.MILLI_OF_SECOND.

int millis = Instant.now().get( ChronoField.MILLI_OF_SECOND ) ;  // Get current moment in UTC, then interrogate a `TemporalField`.

Or do the math yourself.

More likely you are asking this for a specific time zone. The fraction of a second is likely to be the same as with Instant but there are so many anomalies with time zones, I hesitate to make that assumption.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) ;

Interrogate for the fractional second. The Question asked for milliseconds, but java.time classes use a finer resolution of nanoseconds. That means the number of nanoseconds will range from from 0 to 999,999,999.

long nanosFractionOfSecond = zdt.getNano();

If you truly want milliseconds, truncate the finer data by dividing by one million. For example, a half second is 500,000,000 nanoseconds and also is 500 milliseconds.

long millis = ( nanosFractionOfSecond / 1_000_000L ) ;  // Truncate nanoseconds to milliseconds, by a factor of one million.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Solution 5

I tried a few ones above but they seem to reset @ 1000

This one definately works, and should also take year into consideration

long millisStart = Calendar.getInstance().getTimeInMillis();

and then do the same for end time if needed.

Share:
399,355
LemonMan
Author by

LemonMan

Updated on June 29, 2020

Comments

  • LemonMan
    LemonMan almost 4 years

    Note, I do NOT want millis from epoch. I want the number of milliseconds currently on the clock.

    So for example, I have this bit of code.

    Date date2 = new Date(); 
    Long time2 = (long) (((((date2.getHours() * 60) + date2.getMinutes())* 60 ) + date2.getSeconds()) * 1000);
    

    Is there a way to get milliseconds with date? Is there another way to do this?

    Note: System.currentTimeMillis() gives me millis from epoch which is not what I'm looking for.

    • Matt Ball
      Matt Ball almost 12 years
      You mean, "milliseconds in the second," so the value is always in the interval [0, 999], correct? @thinksteep read the last sentence.
    • Basil Bourque
      Basil Bourque almost 9 years
      @Lemonio Giving an example would make your Question more clear.
    • Basil Bourque
      Basil Bourque about 7 years
      FYI, the troublesome old date-time classes such as java.util.Date are now legacy, supplanted by the java.time classes.
    • Basil Bourque
      Basil Bourque over 6 years
      FYI, the troublesome old date-time classes such as java.util.Date are now legacy, supplanted by the java.time classes. See Tutorial by Oracle.
    • Chris Neve
      Chris Neve over 6 years
      @Basil Bourque source?
    • Basil Bourque
      Basil Bourque over 6 years
      @ChrisNeve JEP 150 endorsed by Brian Goetz, JSR 310 adopted unanimously, a technical article published by Oracle, and replacement of old date-time Oracle Tutorial with new java.time Tutorial.
  • kgautron
    kgautron almost 12 years
    The calendar is already current time by default, and there is no s at MILLISECOND.
  • Jon Skeet
    Jon Skeet almost 12 years
    Note that if you travel back in time to before the Unix epoch, this will give a negative value whereas using c.get(Calendar.MILLISECOND) shouldn't. Always think of the corner cases!
  • Markus Mikkolainen
    Markus Mikkolainen almost 12 years
    and if somebody defines a timezone not on second border or adds a leap-millisecond this breaks.=))
  • Vishy
    Vishy almost 12 years
    Calendar is relative inefficient for something so simple.
  • Vishy
    Vishy almost 12 years
    Java doesn't support leap-seconds.
  • R. Martinho Fernandes
    R. Martinho Fernandes almost 12 years
    Java doesn't support time travel.
  • Jon Skeet
    Jon Skeet almost 12 years
    @MarkusMikkolainen: Nope, System.currentTimeMillis() isn't affected by time zones.
  • Markus Mikkolainen
    Markus Mikkolainen almost 12 years
    yes. exactly. that is why that %1000 will break if somebody makes a timezone that is not on the second border. If a timezone starts at .001 , then the %1000 calculation will be off by 1 millisecond.
  • Jon Skeet
    Jon Skeet almost 12 years
    @PeterLawrey: Well, it might or it might not. It's up to the implementation. From the docs for Date: "A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C."
  • Jon Skeet
    Jon Skeet almost 12 years
    @MarkusMikkolainen: Oh, sorry, I see - you mean it will always give the UTC milliseconds rather than the local ones. Yes.
  • Markus Mikkolainen
    Markus Mikkolainen almost 12 years
    and java must support leap-seconds otherwise the date calculations will be off?
  • Markus Mikkolainen
    Markus Mikkolainen almost 12 years
    ofcourse, an old java implementation will only see the leap seconds that were defined before it was released i guess.unless java is smart enough to use operating system timezone definitions or something..
  • Vishy
    Vishy almost 12 years
    So far, Java uses its own TimeZone so its behaviour is the same across platforms. These timezones can have a milli-second offset, but given no TimeZone ever has AFAIK, it seems unlikely it every will.
  • Jonik
    Jonik about 9 years
    Compile error: "getMillis() has protected access"; need to use get() instead. Also note that new DateTime(new Date()) is equivalent to writing simply new DateTime().
  • Basil Bourque
    Basil Bourque almost 9 years
    The method millisOfSecond access an object and the further call to get extracts a primitive int from that object. You can collapse the two calls using the convenience getter method, getMillisOfSecond. Joda-Time follows this pattern for many of its properties.
  • Sean Van Gorder
    Sean Van Gorder almost 8 years
    Answering the wrong question. That's current millis from epoch, not the millis part of the current time.
  • Basil Bourque
    Basil Bourque about 7 years
    [A] This is not what the Question asked for. Expressly says they do not want a count of milliseconds since the epoch reference date. [B] You could shorten that by dropping the ZonedDateTime: Instant.now().toEpochMilli()
  • Basil Bourque
    Basil Bourque about 7 years
    FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
  • Basil Bourque
    Basil Bourque over 4 years
    Does not work in some time zones. In some zones, on some dates, the day may not begin at 00:00:00. And the day may not be 24 hours long, may add or skip some hours or minutes. The LocalDateTime class cannot represent a moment, lacking any concept of time zone or offset-from-UTC, and therefore cannot track these time zone issues.
  • AKTanara
    AKTanara almost 3 years
    No, I confirm that both System and Calendar return exactly same numbers: 1627732708315:1627732708315