Java MonthDay format()方法及示例

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

Java MonthDay format()方法及示例

Java中MonthDay类的 format() 方法使用指定的格式化器来格式化这个月日。

语法

public String format(DateTimeFormatter formatter)

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

返回: 该函数返回格式化的日期字符串,且不为空。

下面的程序说明了 MonthDay.format() 方法。

程序 1 :

// Program to illustrate the format() method  import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter;  public class GfG {    public static void main(String[] args)    {        // Parses the date        MonthDay tm1 = MonthDay.parse("--12-06");          // Uses the function        LocalDate dt1 = tm1.atYear(2018);          DateTimeFormatter formatter            = DateTimeFormatter                  .ofPattern("YYYY-MM-dd");          System.out.println(formatter.format(dt1));    }}

输出。

2018-12-06

程序2

// Program to illustrate the format() method  import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter;  public class GfG {    public static void main(String[] args)    {        // Parses the date        MonthDay tm1 = MonthDay.parse("--10-06");          // Uses the function        LocalDate dt1 = tm1.atYear(2018);          DateTimeFormatter formatter            = DateTimeFormatter                  .ofPattern("--MM-dd");          System.out.println(formatter.format(dt1));    }}

输出。

--10-06

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

相关推荐