简体   繁体   中英

Define a few specific date formatters as members of an enum in Java

I need to track a few formats ( DateTimeFormatter objects) for repeated use in my app.

➥ How to represent these formatter objects by using a Java enum?

tl;dr

Yes.

FormatDateOnly.DD_MM_YYYY.getFormatter()

Details

Yes, you can easily store some DateTimeFormatter objects in an enum.

The slick enum facility in Java is quite powerful and flexible.

Basically, an enum in Java is almost a normal Java class. Your enum can have member variables to store objects internally. Your enum can have a constructor, and you can pass arguments to those constructors. You can define methods on your enum.

Let's put those 3 features together in this example class, FormatDateOnly enum class.

We define 3 objects in this enum, named DD_MM_YYYY , YYYY_MM_DD , and MM_DD_YYYY . When constructing each, we assign a DateTimeFormatter object to be held in this enum. Because java.time classes ( tutorial ) are immutable and designed to be thread-safe , we can hold a single instance for reuse even across threads. The way enums work in Java is that an instance of that when our class FormatDateOnly is first loaded, each of our three constructors is called to make an instance assigned to each name.

We also pass a string to use as the display-name of each enum. We see this used in the toString override method.

package work.basil.example;

import java.time.format.DateTimeFormatter;

public enum FormatDateOnly
{
    DD_MM_YYYY( DateTimeFormatter.ofPattern( "dd.MM.uuuu" ) , "DD.MM.YYYY" ),
    YYYY_MM_DD( DateTimeFormatter.ofPattern( "uuuu.MM.dd" ) , "YYYY.MM.DD" ),
    MM_DD_YYYY( DateTimeFormatter.ofPattern( "MM.dd.uuuu" ) , "MM.DD.YYYY" );

    private DateTimeFormatter formatter;
    private String displayName;

    FormatDateOnly ( DateTimeFormatter formatter , String displayName )
    {
        this.formatter = formatter;
        this.displayName = displayName;
    }

    @Override
    public String toString ( )
    {
        return "LocalDateFormat{" +
                "displayName='" + this.displayName + '\'' +
                '}';
    }

    public DateTimeFormatter getFormatter ( )
    {
        return this.formatter;
    }

    public String getDisplayName ( )
    {
        return this.displayName;
    }
}

To use these enums, we refer to the desired enum object, then call the getter method to retrieve the stored DateTimeFormatter stored within that enum object.

LocalDate localDate = LocalDate.of( 2020 , Month.JANUARY , 23 );

String output1 = localDate.format( FormatDateOnly.DD_MM_YYYY.getFormatter() );
String output2 = localDate.format( FormatDateOnly.MM_DD_YYYY.getFormatter() );
String output3 = localDate.format( FormatDateOnly.YYYY_MM_DD.getFormatter() );
  • The first part FormatDateOnly.DD_MM_YYYY refers to one of the three pre-existing objects (instantiated when class loaded).
  • The second part, .getFormatter() invokes the getter method on that particular enum object to retrieve the existing DateTimeFormatter object passed to the enum's constructor.

Dump to console. Running on Java 13.

System.out.println( "localDate.toString() = " + localDate );
System.out.println( "output1 = " + output1 );
System.out.println( "output2 = " + output2 );
System.out.println( "output3 = " + output3 );

localDate.toString() = 2020-01-23

output1 = 23.01.2020

output2 = 01.23.2020

output3 = 2020.01.23


By the way, I am not necessarily recommending this arrangement. Generally it is better to let java.time automatically localize when generating text representing a date-time object. Specify a FormatStyle for how long or abbreviate you want the resulting string. Specify a Locale to determine the human language and cultural norms needed for localization.

Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale ) ;
String output = localDate.format( formatter ) ;

20-01-23

In addition to Formating the same approach can be used for parsing also

import java.text.SimpleDateFormat;

public enum StandardDateParser {
    YYYY_MM_DD(new SimpleDateFormat("yyyy-MM-dd"), "yyyy-MM-dd"),
    YYYYMMDD(new SimpleDateFormat("yyyyMMdd"), "yyyyMMdd"),
    YYYY_MM_DD_HH_MM_SS(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"),
    YYYY_MM_DDTHH_MM_SSZ(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"), "yyyy-MM-dd'T'HH:mm:ssZ");

    SimpleDateFormat parser;
    private String displayName;

    StandardDateParser(SimpleDateFormat parser, String displayName) {
        this.parser = parser;
        this.displayName = displayName;
    }

    @Override
    public String toString() {
        return displayName;
    }

    public SimpleDateFormat getParser() {
        return this.parser;
    }

    public String getDisplayName() {
        return this.displayName;
    }
}

Use:

SimpleDateFormat parser = StandardDateParser.YYYY_MM_DDTHH_MM_SSZ.getParser();
Date date;
try {
    date = parser.parse(INPUT_STRING)
} catch (ParseException e) {
    // your fall back code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM