📜  Java中的Java .time.format.DateTimeFormatterBuilder 类

📅  最后修改于: 2022-05-13 01:54:39.741000             🧑  作者: Mango

Java中的Java .time.format.DateTimeFormatterBuilder 类

DateTimeFormatterBuilder Class是用于创建日期时间格式化程序的构建器类。 DateTimeFormatter 用作 Formatter 用于打印和解析日期时间对象。 DateTimeFormatterBuilder 允许创建 DateTimeFormatter。 DateTimeFormatterBuilder 用于构造格式化程序,然后用于打印或解析。格式化程序是通过将特定字段或其他格式化程序附加到此构建器的实例来构建的。如果我们想创建我们自己的 DateTimeFormatter 对象,那么Java.time.format.DateTimeFormatterBuilder 会有所帮助。所有日期时间格式化程序最终都是使用此构建器创建的。

句法:

public final class DateTimeFormatterBuilder
extends Object

在深入研究这个类的方法之前,让我们先讨论这个类的构造函数

ConstructorDescription
DateTimeFormatterBuilder()Constructs a new instance of the builder.

方法:

让我们讨论在这个类中声明的这个类中存在的方法,如下所示:

clone()
equals()
finalize()
getClass()
hashCode()
notify()
notifyAll()
toString()
wait() 

它们在下面以表格形式按字母顺序与它们所执行的操作一起以图形方式描述,如下所示:

MethodsAction Performed 
append(DateTimeFormatter formatter)Appends all the elements of a formatter to the builder.
appendChronologyId()Appends the chronology ID, such as ‘ISO’ or ‘ThaiBuddhist’, to the formatter.
appendChronologyText(TextStyle textStyle)Appends the chronology name to the formatter.
appendFraction(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint)Appends the fractional value of a date-time field to the formatter.
appendInstant()Appends an instant using ISO-8601 to the formatter, formatting fractional digits in groups of three.
appendInstant(int fractionalDigits)Appends an instant using ISO-8601 to the formatter with control over the number of fractional digits.
appendLiteral(char literal)Appends a character literal to the formatter.
appendLiteral(String literal)Appends a string literal to the formatter.
appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle)Appends a localized date-time pattern to the formatter.
appendLocalizedOffset(TextStyle style)Appends the localized zone offset, such as ‘GMT+01:00’, to the formatter.
appendOffset(String pattern, String noOffsetText)Appends the zone offset, such as ‘+01:00’, to the formatter.
appendOffsetId()Appends the zone offset, such as ‘+01:00’, to the formatter.
appendOptional(DateTimeFormatter formatter)Appends a formatter to the builder which will optionally format/parse.
appendPattern(String pattern)Appends the elements defined by the specified pattern to the builder.
appendText(TemporalField field)Appends the text of a date-time field to the formatter using the full-text style.
appendText(TemporalField field, Map textLookup)Appends the text of a date-time field to the formatter using the specified map to supply the text.
appendText(TemporalField field, TextStyle textStyle)Appends the text of a date-time field to the formatter.
appendValue(TemporalField field)Appends the value of a date-time field to the formatter using a normal output style.
appendValue(TemporalField field, int width)Appends the value of a date-time field to the formatter using a fixed width, zero-padded approach.
appendValue(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle)Appends the value of a date-time field to the formatter providing full control over formatting.
appendValueReduced(TemporalField field, int width, int maxWidth, ChronoLocalDate baseDate)Appends the reduced value of a date-time field to the formatter.
appendValueReduced(TemporalField field, int width, int maxWidth, int baseValue)Appends the reduced value of a date-time field to the formatter.
appendZoneId()Appends the time-zone ID, such as ‘Europe/Paris’ or ‘+02:00’, to the formatter.
appendZoneOrOffsetId()Appends the time-zone ID, such as ‘Europe/Paris’ or ‘+02:00’, to the formatter, using the best available zone ID.
appendZoneRegionId()Appends the time-zone region ID, such as ‘Europe/Paris’, to the formatter, rejecting the zone ID if it is a ZoneOffset
appendZoneText(TextStyle textStyle)Appends the time-zone name, such as ‘British Summer Time’, to the formatter.
appendZoneText(TextStyle textStyle, Set preferredZones)Appends the time-zone name, such as ‘British Summer Time’, to the formatter.
getLocalizedDateTimePattern()Gets the formatting pattern for date and time styles for a locale and chronology.
optionalEnd()Ends an optional section.
optionalStart()Mark the start of an optional section.
padNext(int padWidth)Causes the next added printer/parser to pad to a fixed width using a space.
padNext(int padWidth, char padChar)Causes the next added printer/parser to pad to a fixed width.
parseCaseInsensitive()Changes the parse style to be case insensitive for the remainder of the formatter.
parseCaseSensitive()Changes the parse style to be case-sensitive for the remainder of the formatter.
parseDefaulting()Appends a default value for a field to the formatter for use in parsing.
parseLenient()Changes the parse style to be lenient for the remainder of the formatter.
parseStrict()Changes the parse style to be strict for the remainder of the formatter.
 toFormatter()Completes this builder by creating the DateTimeFormatter using the default locale.
toFormatter(Locale locale)Completes this builder by creating the DateTimeFormatter using the specified locale.

现在让我们在干净的Java程序的帮助下通过调用这个类的一些方法来实现,通过实现它的方法来更好地理解这个类。

执行:

示例 1

Java
// Java Program to illustrate DateTimeFormatterBuilder class
// by invoking appendValue() Method of this class
  
// Importing required classes from respective packages
import java.io.*;
import java.lang.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating an object of this class
        DateTimeFormatterBuilder builder
            = new DateTimeFormatterBuilder();
  
        // Now creating object of DateTimeFormatter class
        // over which appendValue() method is invoked
        DateTimeFormatter formatter
            = builder.appendLiteral("Day is:")
                  .appendValue(ChronoField.DAY_OF_MONTH)
                  .appendLiteral(", month is:")
                  .appendValue(ChronoField.MONTH_OF_YEAR)
                  .toFormatter();
  
        // Creating object of LocalDateTime class
        // invoking now() method over it
        LocalDateTime dateTime = LocalDateTime.now();
  
        String str = dateTime.format(formatter);
  
        // Print and display the day and month
        System.out.println(str);
    }
}


Java
// Java program to illustrate DateTimeFormatterBuilder
// Using optionalStart() and optionalEnd() Methods
  
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
  
// Main class
public class GFG {
  
    // Main driver methods
    public static void main(String[] args)
    {
  
        // Creating an object of DateTimeFormatter class
        DateTimeFormatter parser
            = new DateTimeFormatterBuilder()
                  .appendPattern("[yyyy][yyyyMM][yyyyMMdd]")
                  .optionalStart()
                  .parseDefaulting(
                      ChronoField.MONTH_OF_YEAR, 1)
                  .parseDefaulting(ChronoField.DAY_OF_MONTH,
                                   1)
                  .optionalEnd()
                  .toFormatter();
  
        // Print and display statements
  
        // Execute if only year is given in parameter
        System.out.println(
            parser.parse("2021", LocalDate::from));
  
        // Execute if year and month is given
        System.out.println(
            parser.parse("202106", LocalDate::from));
  
        // Execute if year, month and date is given
        System.out.println(
            parser.parse("20210631", LocalDate::from));
    }
}


Java
// Java program to illustrate DateTimeFormatterBuilder class
  
// Importing required classes from respective packages
import java.io.*;
import java.lang.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
import java.util.Locale;
  
// Main class
// DateTimeFormatterBuilderExample
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creat
        LocalDate date = LocalDate.of(2021, 6, 30);
  
        // Creaating object of DateTimeFormatter class to
        //
  
        // Object 1
        DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("dd/MM/yyyy");
  
        // Object 2
        DateTimeFormatter italianFormatter
            = DateTimeFormatter.ofPattern("d. MMMM yyyy",
                                          Locale.ITALIAN);
  
        // Print and display date in format XX-XX-XX
        System.out.println(
            date.format(DateTimeFormatter.ISO_LOCAL_DATE));
  
        // Print and display date in format XX/XX/XX
        System.out.println(date.format(formatter));
  
        // Print and display Italian date formatter
        System.out.println(date.format(italianFormatter));
  
        // Object 3
        DateTimeFormatter complexFormatter
            = new DateTimeFormatterBuilder()
                  .appendText(ChronoField.DAY_OF_MONTH)
                  .appendLiteral(". ")
                  .appendText(ChronoField.MONTH_OF_YEAR)
                  .appendLiteral(" ")
                  .appendText(ChronoField.YEAR)
                  .parseCaseInsensitive()
                  .toFormatter(Locale.US);
  
        // Print ad display US date formatter
        System.out.println(date.format(complexFormatter));
    }
}


输出
Day is:7, month is:7

示例 2

optionalStart() 和 optionalEnd() 方法

Java

// Java program to illustrate DateTimeFormatterBuilder
// Using optionalStart() and optionalEnd() Methods
  
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
  
// Main class
public class GFG {
  
    // Main driver methods
    public static void main(String[] args)
    {
  
        // Creating an object of DateTimeFormatter class
        DateTimeFormatter parser
            = new DateTimeFormatterBuilder()
                  .appendPattern("[yyyy][yyyyMM][yyyyMMdd]")
                  .optionalStart()
                  .parseDefaulting(
                      ChronoField.MONTH_OF_YEAR, 1)
                  .parseDefaulting(ChronoField.DAY_OF_MONTH,
                                   1)
                  .optionalEnd()
                  .toFormatter();
  
        // Print and display statements
  
        // Execute if only year is given in parameter
        System.out.println(
            parser.parse("2021", LocalDate::from));
  
        // Execute if year and month is given
        System.out.println(
            parser.parse("202106", LocalDate::from));
  
        // Execute if year, month and date is given
        System.out.println(
            parser.parse("20210631", LocalDate::from));
    }
}
输出
2021-01-01
2021-06-01
2021-06-30

示例 3

Java

// Java program to illustrate DateTimeFormatterBuilder class
  
// Importing required classes from respective packages
import java.io.*;
import java.lang.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.time.temporal.ChronoField;
import java.util.Locale;
  
// Main class
// DateTimeFormatterBuilderExample
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creat
        LocalDate date = LocalDate.of(2021, 6, 30);
  
        // Creaating object of DateTimeFormatter class to
        //
  
        // Object 1
        DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("dd/MM/yyyy");
  
        // Object 2
        DateTimeFormatter italianFormatter
            = DateTimeFormatter.ofPattern("d. MMMM yyyy",
                                          Locale.ITALIAN);
  
        // Print and display date in format XX-XX-XX
        System.out.println(
            date.format(DateTimeFormatter.ISO_LOCAL_DATE));
  
        // Print and display date in format XX/XX/XX
        System.out.println(date.format(formatter));
  
        // Print and display Italian date formatter
        System.out.println(date.format(italianFormatter));
  
        // Object 3
        DateTimeFormatter complexFormatter
            = new DateTimeFormatterBuilder()
                  .appendText(ChronoField.DAY_OF_MONTH)
                  .appendLiteral(". ")
                  .appendText(ChronoField.MONTH_OF_YEAR)
                  .appendLiteral(" ")
                  .appendText(ChronoField.YEAR)
                  .parseCaseInsensitive()
                  .toFormatter(Locale.US);
  
        // Print ad display US date formatter
        System.out.println(date.format(complexFormatter));
    }
}
输出
2021-06-30
30/06/2021
30. giugno 2021
30. June 2021