将一些特定的日期格式设置为Java枚举的成员

问题描述 投票:0回答:1

我需要跟踪一些格式(DateTimeFormatter对象),以便在我的应用中重复使用。

➥如何通过使用Java枚举来表示这些格式化程序对象?

java enums java-time formatter dateformatter
1个回答
0
投票

tl; dr

DateTimeFormatter

详细信息

是,您可以轻松地将某些FormatDateOnly.DD_MM_YYYY.getFormatter() 对象存储在枚举中。

光滑的DateTimeFormatter非常强大而灵活。

[基本上,Java中的枚举几乎是一个普通的Java类。您的枚举可以具有成员变量以在内部存储对象。您的枚举可以有一个构造函数,并且可以将参数传递给那些构造函数。您可以在枚举中定义方法。

在示例类DateTimeFormatter枚举类中将这3个功能放在一起。

我们在此枚举中定义了3个对象,分别命名为enum facility in JavaFormatDateOnlyDD_MM_YYYY。在构造每个对象时,我们分配一个YYYY_MM_DD对象以保留在此枚举中。因为java.time类(MM_DD_YYYY)是DateTimeFormatter且设计为tutorial,所以我们甚至可以在线程之间保留单个实例以进行重用。在Java中枚举的工作方式是,当我们的类immutable首次加载时,该类的一个实例将调用我们的三个构造函数中的每一个,以使实例分配给每个名称。

我们还传递了一个字符串,用作每个枚举的显示名称。我们看到它在thread-safe覆盖方法中使用。

FormatDateOnly

要使用这些枚举,我们引用所需的枚举对象,然后调用getter方法以检索存储在该枚举对象中的存储的toString

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;
    }
}
  • 第一部分DateTimeFormatter引用三个预先存在的对象之一(在加载类时实例化)。
  • [第二部分,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() ); 在该特定枚举对象上调用getter方法,以检索传递给枚举的构造函数的现有FormatDateOnly.DD_MM_YYYY对象。

转储到控制台。在Java 13上运行。

.getFormatter()

localDate.toString()= 2020-01-23

输出1 = 23.01.2020

输出2 = 01.23.2020

输出3 = 2020.01.23


顺便说一句,我不一定推荐这种安排。通常,在生成表示日期时间对象的文本时,最好让java.time DateTimeFormatter。指定System.out.println( "localDate.toString() = " + localDate ); System.out.println( "output1 = " + output1 ); System.out.println( "output2 = " + output2 ); System.out.println( "output3 = " + output3 ); 表示想要的结果字符串的长度或缩写。指定automatically localize以确定本地化所需的人类语言和文化规范。

FormatStyle

20-01-23

© www.soinside.com 2019 - 2024. All rights reserved.