I want an easy way to generate exactly the same result as the JavaScript Date function but in Java.
Javascript:
> new Date()
Sat Jul 02 2022 22:49:06 GMT-0800 (Alaska Daylight Time)
Java:
> System.out.println(new Date());
Sat Jul 02 22:49:06 AKDT 2022
Want:
> System.out.println(new Date());
Sat Jul 02 2022 22:49:06 GMT-0800 (Alaska Daylight Time)
CodePudding user response:
We can use the latest Java 8 date API with a custom timestamp format string:
ZonedDateTime zdt = ZonedDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM d yyyy HH:mm:ss OOOO (zzzz)");
System.out.println(dtf.format(zdt));
On the demo tool where I tried this (which server happens to be in Europe), I got this output:
Sun Jul 3 2022 09:14:27 GMT 02:00 (Central European Summer Time)