Java中的 LocalTime format() 方法及示例
LocalTime 类的format()方法用于使用作为参数传递的指定格式化程序来格式化此时间。此方法基于将格式化程序传递给字符串来格式化这次。
句法:
public String format(DateTimeFormatter formatter)
参数:此方法接受单个参数格式化程序,它是指定的格式化程序。它不应该为空。
返回值:该方法返回格式化的时间字符串。
异常:如果在打印过程中发生错误,此方法将引发DateTimeException 。
下面的程序说明了 format() 方法:
方案一:
// Java program to demonstrate
// LocalTime.format() method
import java.time.*;
import java.time.format.DateTimeFormatter;
public class GFG {
public static void main(String[] args)
{
// create a LocalTime Objects
LocalTime time
= LocalTime.parse("03:18:23");
// create formatter Object
DateTimeFormatter formatter
= DateTimeFormatter.ISO_TIME;
// apply format
String value = time.format(formatter);
// print result
System.out.println("value : "
+ value);
}
}
输出:
value : 03:18:23
方案二:
// Java program to demonstrate
// LocalTime.format() method
import java.time.*;
import java.time.format.DateTimeFormatter;
public class GFG {
public static void main(String[] args)
{
// create a LocalTime Objects
LocalTime time
= LocalTime.parse("23:59:59");
// create formatter Object for ISO_LOCAL_TIME
DateTimeFormatter formatter
= DateTimeFormatter.ISO_LOCAL_TIME;
// apply format
String value = time.format(formatter);
// print result
System.out.println("value : "
+ value);
}
}
输出:
value : 23:59:59
参考: https: Java Java.time.format.DateTimeFormatter)