Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách lấy ngày giờ trong JShell Java 9

JShell (Java 9 REPL) cho phép học, khám phá Java API tức thì – không cần class verbose có main().

Lấy current date-time

C:\Users\User> jshell
| Welcome to JShell -- Version 9.0.4
jshell> new Date()
$1 ==> Fri Feb 28 11:59:23 IST 2020

Lấy timestamp (milliseconds since epoch)

jshell> new Date().getTime()
$2 ==> 1582871487654
jshell> System.currentTimeMillis()
$3 ==> 1582871513421
jshell> new Date(1582871513421L)
$4 ==> Fri Feb 28 12:01:53 IST 2020

Java Time API (java.time) – Khuyên dùng

jshell> java.time.Instant.now()
$5 ==> 2020-02-28T07:07:33.941720100Z

jshell> java.time.LocalDate.now()
$6 ==> 2020-02-28

jshell> java.time.LocalTime.now()
$7 ==> 11:59:45.123456789

jshell> java.time.LocalDateTime.now()
$8 ==> 2020-02-28T11:59:45.123456789

jshell> java.time.ZonedDateTime.now()
$9 ==> 2020-02-28T11:59:45.123456789+05:30[Asia/Kolkata]

So sánh Date vs java.time

Đặc điểmjava.util.Datejava.time (Java 8+)
Thread-safeKhông (mutable)Có (immutable)
APILỗi thời, deprecated methodsHiện đại, fluent, rich
TimezonePhức tạp (Calendar)ZoneId, ZonedDateTime rõ ràng
PrecisionMillisecondNanosecond
FormattingSimpleDateFormat (not thread-safe)DateTimeFormatter (thread-safe)

Format tùy chỉnh trong JShell

jshell> java.time.format.DateTimeFormatter fmt = java.time.format.DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
jshell> java.time.LocalDateTime.now().format(fmt)
$11 ==> "28/02/2020 12:05:30"

JShell + java.time = công cụ mạnh khám phá, test date-time logic, timezone, formatting.