How to get the current date and time

后端 未结 10 531
无人共我
无人共我 2020-11-29 16:59

How do I get the current date and time in Java?

I am looking for something that is equivalent to DateTime.Now from C#.

10条回答
  •  悲哀的现实
    2020-11-29 17:58

    Java has always got inadequate support for the date and time use cases. For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe which can lead to concurrency issues. Also there are certain flaws in API. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive. These issues led to popularity of third-party date and time libraries, such as Joda-Time. To address a new date and time API is designed for Java SE 8.

    LocalDateTime timePoint = LocalDateTime.now();
    System.out.println(timePoint);
    

    As per doc:

    The method now() returns the current date-time using the system clock and default time-zone, not null. It obtains the current date-time from the system clock in the default time-zone. This will query the system clock in the default time-zone to obtain the current date-time. Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

提交回复
热议问题