Any new method to get current time with accuracy in microseconds in Java now?

后端 未结 3 524
清歌不尽
清歌不尽 2020-12-11 01:40

I checked the below page that there is no method to get current time with accuracy in microsecond in Java in 2009.
Current time in microseconds in java

The best

3条回答
  •  情歌与酒
    2020-12-11 02:37

    The Java 8 java.time package has what you need.

    Try:

    LocalDateTime.now(); // The current timestamp accurate to nanoseconds
    LocalDateTime.now().getLong(ChronoField.MICRO_OF_SECOND); // the microseconds part
    LocalDateTime.now().getLong(ChronoField.NANO_OF_SECOND); // even finer
    LocalDateTime.now().getDayOfMonth(); // main parts of the date have their own methods
    LocalDateTime.now().getMonth(); // etc  
    

    To just get nanos as a String, use nnnnnnnnn in the format:

    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnnnnn"));  
    

提交回复
热议问题