Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get system time in Java without creating a new Date

I need to get the system date, and Java provides the new Date().getTime().

But I need to avoid new object allocation (I'm working on a embedded system). How can I get the system time without allocating a new Date object?

like image 751
michelemarcon Avatar asked Feb 01 '11 14:02

michelemarcon


People also ask

How do I get a time without date in Java?

You can use LocalTime in java. time built into Java 8 and later (Tutorial), or LocalTime from Joda-Time otherwise. These classes represent a time-of-day without a date nor a time zone. LocalTime localTime = LocalTime.

How can I get system time in Java?

Java. time. LocalTime − This class represents a time object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current time from the system clock.

How do you set a specific time in Java?

The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT. Parameters: The function accepts a single parameter time which specifies the number of milliseconds. Return Value: It method has no return value.

How do I get system on time?

To retrieve the system time, use the GetSystemTime function. GetSystemTime copies the time to a SYSTEMTIME structure that contains individual members for month, day, year, weekday, hour, minute, second, and milliseconds. It is easy to display this format to a user.


1 Answers

As jzd says, you can use System.currentTimeMillis. If you need it in a Date object but don't want to create a new Date object, you can use Date.setTime to reuse an existing Date object. Personally I hate the fact that Date is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar has a setTimeInMillis method.

If possible though, it would probably be better just to keep it as a long. If you only need a timestamp, effectively, then that would be the best approach.

like image 128
Jon Skeet Avatar answered Sep 18 '22 13:09

Jon Skeet