Java year format()方法及实例
Java中Year类的 format() 方法用于根据作为参数传递给它的DateTimeFormatter来格式化当前的Year对象。
语法:
public String format(DateTimeFormatter formatter)
参数 :该方法接受一个单参数formatter。它指定了一个DateTimeFormatter,当前的Year对象将据此进行格式化。它不能是NULL。
返回值 :它返回一个字符串,这是格式化的年份值。
异常 :如果在格式化年对象的过程中发生任何错误,该方法将抛出一个 DateTimeException 。
下面的程序说明了Java中year的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) { // Creates a Year object Year firstYear = Year.of(1997); // Print the current year in // default format System.out.println(firstYear); // Create a DateTimeFormatter DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy"); // Print the current year after formatting System.out.println(firstYear.format(formatter)); }}
输出:
199797
程序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) { // Creates a Year object Year firstYear = Year.of(2018); // Print the current year in // default format System.out.println(firstYear); // Create a DateTimeFormatter DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy"); // Print the current year after formatting System.out.println(firstYear.format(formatter)); }}输出:
201818
参考资料 :
https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#format-java.time.format.DateTimeFormatter-
