michelemarcon
michelemarcon

Reputation: 24767

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?

Upvotes: 43

Views: 200711

Answers (4)

Aravind Yarram
Aravind Yarram

Reputation: 80176

Use System.currentTimeMillis() or System.nanoTime().

Upvotes: 8

Mark Elliot
Mark Elliot

Reputation: 77044

You can use System.currentTimeMillis().

At least in OpenJDK, Date uses this under the covers.

The call in System is to a native JVM method, so we can't say for sure there's no allocation happening under the covers, though it seems unlikely here.

Upvotes: 12

Jon Skeet
Jon Skeet

Reputation: 1500345

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.

Upvotes: 64

jzd
jzd

Reputation: 23629

This should work:

System.currentTimeMillis();

Upvotes: 53

Related Questions