unwichtich
unwichtich

Reputation: 13857

Java 8 Date/Time API equivalent of 'new Date().toString()'

Is there an equivalent to new Date().toString() (Date from java.util.Date) in Java 8's new Date-Time API?

If I do the following:

System.out.println(new Date());

this gives me by default a nice readable result like this:

Sat Jan 03 12:58:46 CET 2015

(depends a little bit on the locale)

In Java 8 (the new ways, I know that the above way is still working) I see the following ways to get a date string "directly" (without additional formatting):

System.out.println(Clock.systemUTC().instant());

results in something like:

2015-01-03T12:03:58.614Z

This is not really readable and requires some additional formatting.

Another way:

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

results in:

2015-01-03T13:00:58.594

This is nearly the same as the last one, but without the timezone Z at the end.

Because the desired date string should also contain the timezone, I tried the following:

System.out.println(ZonedDateTime.now());

This prints:

2015-01-03T13:00:35.277+01:00[Europe/Berlin]

which is also unusable.

I know that I can easily format the date by passing an instance of DateTimeFormatter to the format() method of ZonedDateTime or by using one of the existing ones like this:

System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME));

prints out:

Sat, 3 Jan 2015 13:01:25 +0100

which would be acceptable for me as result. But it requires additional formatting, which is what I want to avoid.

So, is there a way to get something similar if not equivalent to new Date().toString() with the new Java 8 Date-Time classes?

Upvotes: 2

Views: 1200

Answers (1)

JodaStephen
JodaStephen

Reputation: 63465

You need to use a formatter to replicate the format of java.util.Date. Declare the formatter using a pattern:

private static final DateTimeFormatter FORMATTER =
    DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");

(using a static constant is recommended)

Then use a ZonedDateTime and format it using one of these methods:

ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt.format(FORMATTER));
System.out.println(FORMATTER.format(zdt));

See also DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG) for more localized formats.

Upvotes: 2

Related Questions