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

前端 未结 4 1788
抹茶落季
抹茶落季 2020-12-28 12:36

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)

4条回答
  •  长情又很酷
    2020-12-28 13:01

    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.

提交回复
热议问题