Skip to content
Advertisement

How to get the time of the day in milliseconds?

I want to get the time of a day in milliseconds, I do not this day to have any specific date, just a time. I made something, thought it worked, but then went debugging and concluded that it doesn’t work how I want it to.

I want to use this to check if the current time is between both my specified startTime and endTime.

JavaScript

How I am setting the time of the propeties startTime and endTime:

JavaScript

However this will mean that both startTimeand endTime will have this a specific date attached to it.

I hope I explained it well, any help is appreciated!

Advertisement

Answer

Avoid Milliseconds

No need to mess with milliseconds for your purpose. Using milliseconds for date-time is confusing and error-prone.

What you need is a decent date-time library rather than the notoriously troublesome bundled java.util.Date & .Calendar classes.

Joda-Time

If you are certain you want to ignore dates and ignore time zones, here’s some example code using the LocalTime class offered by the third-party free-of-cost Joda-Time library.

JavaScript

Adjust that last line according to your business logic needs. You might want:

  • The beginning and ending are inclusive
  • The beginning and ending are exclusive
  • Half-Open” where the beginning is inclusive and the ending is exclusive
    (usually best for date-time work)

Dump to console…

JavaScript

When run…

JavaScript

Another Example

Time-of-day-only is not usually the right way to go. When new to date-time work, a naïve programmer may at first think that time-only simplifies things. On the contrary, this example shows how spinning around the clock creates complications. Using date+time+timeZone is usually the best approach in the long run.

JavaScript

When run…

JavaScript

java.time

Java 8 brings the new java.time package, inspired by Joda-Time, defined by JSR 310.

In java.time, you will find a LocalTime class similar to the one in Joda-Time.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement