Java ChronoLocalDate format()方法及示例

来源:这里教程网 时间:2026-02-17 20:38:54 作者:

Java ChronoLocalDate format()方法及示例

Java中ChronoLocalDate接口的format()方法使用指定的格式化器格式化这个日期。

语法:

public String format(DateTimeFormatter formatter)

参数 :该方法接受一个参数obj,该参数指定了要使用的格式,它不是空的。

异常 :该函数只抛出在打印过程中出现的DateTimeException错误。

返回值 :它返回格式化的日期字符串,而不是空值。

以下程序说明了Java中ChronoLocalDate的 format() 方法。

程序1 :

// Program to illustrate the format() method  import java.util.*;import java.time.*;import java.time.chrono.*;import java.time.format.DateTimeFormatter;  public class GfG {    public static void main(String[] args)    {          // Parses the date        ChronoLocalDate dt            = LocalDate.parse("2018-11-01");        System.out.println(dt);          // Function call        DateTimeFormatter formatter            = DateTimeFormatter                  .ofPattern("dd/MM/YYYY");          System.out.println(formatter.format(dt));    }}

输出。

2018-11-0101/11/2018

方案2 :为了说明这个例外情况。

// Program to illustrate the format() method// Exception Program  import java.util.*;import java.time.*;import java.time.chrono.*;import java.time.format.DateTimeFormatter;  public class GfG {    public static void main(String[] args)    {        try {            // Parses the date            ChronoLocalDate dt                = LocalDate.parse("2018-01-32");            System.out.println(dt);              // Function call            DateTimeFormatter formatter                = DateTimeFormatter                      .ofPattern("dd/MM/YYYY");              System.out.println(formatter.format(dt));        }        catch (Exception e) {            System.out.println(e);        }    }}

输出。

java.time.format.DateTimeParseException:  Text '2018-01-32' could not be parsed: Invalid value for DayOfMonth (valid values 1 - 28/31): 32

参考资料 : https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDate.html#format-java.time.format.DateTimeFormatter-

相关推荐