📜  Java中的 YearMonth format() 方法

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

Java中的 YearMonth format() 方法

Java中 YearMonth 类的 format() 方法用于根据作为参数传递给该方法的年月的指定 DateTimeFormatter 来格式化此 YearMonth 实例。

语法

public String format(DateTimeFormatter formatter)

参数:此方法接受单个参数格式化程序,它是 DateTimeFormatter,根据该参数格式化此 YearMonth 实例。
返回值:根据指定的格式化程序格式化后,将这个YearMonth的值作为字符串返回。
下面的程序说明了Java中 YearMonth 的 format() 方法:
程序 1

Java
// 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)
    {
 
        // Create a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2017, 8);
 
        // Create a DateTimeFormatter string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/MM");
 
        // Format this year-month
        System.out.println(thisYearMonth.format(formatter));
    }
}


Java
// 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)
    {
 
        // Create a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2018, 5);
 
        // Create a DateTimeFormatter string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy");
 
        // Format this year-month
        System.out.println(thisYearMonth.format(formatter));
    }
}


输出:
17/08

方案二

Java

// 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)
    {
 
        // Create a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2018, 5);
 
        // Create a DateTimeFormatter string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/yy");
 
        // Format this year-month
        System.out.println(thisYearMonth.format(formatter));
    }
}
输出:
05/18

参考:https: Java/time/YearMonth.html#format-java.time.format.DateTimeFormatter-