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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With