Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Setting global time formatters

I want to set my own DateTimeFormatter as the global formatter. When I do the following line:

ZonedDateTime.now();

I get:

2016-03-30T08:58:54.180-06:00[America/Chicago]

If I do this:

ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME)

I get:

Wed, 30 Mar 2016 9:00:06 -0600

I want what's printed above but with am/pm so I made my custom formatter and printed out the time like so:

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss a Z");

ZonedDateTime.now().format(FORMATTER);

Which gave me:

Wed, 30 Mar 2016 9:00:06 AM -0600

But I use this .now() method everywhere for logging purposes and I dont want to define the formatter everywhere in the code. Is there a way to configure the formatter as the default format to use when calling the .now() method? I'm thinking like spring bean configuration method or something.....

like image 502
Richard Avatar asked Mar 30 '16 14:03

Richard


People also ask

Which time format is followed in Java 8?

The ISO date-time formatter that formats or parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'. The ISO time formatter that formats or parses a time with an offset, such as '10:15+01:00' or '10:15:30+01:00'.

How do I format a date in Java 8?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); System. out. println(sdf.

What is the format of LocalTime?

LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30. 123456789" can be stored in a LocalTime .


1 Answers

You could simply declare a constant in a class:

class UtilsOrWhatever {
  public static final DateTimeFormater RFC_1123_DATE_TIME_AM_PM = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy hh:mm:ss a Z");
}

and simply use in your code:

ZonedDateTime.now().format(RFC_1123_DATE_TIME_AM_PM); //needs a static import

Alternatively, with pure Java EE 7, you could create a DateTimeFormatter Producer with @Produces and then simply @Inject it.

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;

@ApplicationScoped
public class RfcFormatterProducer {
  @Produces
  private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy hh:mm:ss a Z");
}

In your code:

@Inject DateTimeFormatter rfc;

You could also give it a name like in the link above if you have several formatters.

like image 170
assylias Avatar answered Sep 20 '22 04:09

assylias