I need a function that gives me how many seconds passed from the midnight. I am currently using System.currentTimeMillis()
but it gives me the UNIX like timestamp.
It would be a bonus for me if I could get the milliseconds too.
I need a function that gives me how many seconds passed from the midnight. I am currently using System.currentTimeMillis()
but it gives me the UNIX like timestamp.
It would be a bonus for me if I could get the milliseconds too.
java.time
Using the
java.time
framework built into Java 8 and later. See Tutorial.It is good practice to explicit specify
ZoneId
, even if you want default one.Like @secmask, if you need milli-seconds since GMT midnight, try
The simplest and fastest method to get the seconds since midnight for the current timezone:
One-time setup:
If you use Apache Commons, you can use DateUtils.DAY_IN_MILLIS, otherwise define:
And then, whenever you need the time...:
Note that you'll need to re-setup if there's a possibility that your program will run long enough, and Daylight Saving Times change occurs...
If you're using Java >= 8, this is easily done :
If you're using Java 7 or less, you have to get the date from midnight via Calendar, and then substract.
Use getTime().getTime() instead of getTimeInMillis() if you get an error about calendar being protected. Remember your imports:
will include them all while you are debugging: