Java OffsetDateTime format()方法及示例
Java中OffsetDateTime类的 format() 方法使用指定的格式化器来格式化这个日期时间。
语法:
public String format(DateTimeFormatter formatter)
参数: 该方法接受一个参数 formatter ,指定使用的格式,不为空。
返回值: 它返回格式化的日期字符串,不为空。
异常 :该函数抛出一个 DateTimeException ,即在打印过程中出现错误。
以下程序说明format()方法:
程序1 :
// Java program to demonstrate the format() methodimport java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse("2018-12-12T13:30:30+05:00"); // Prints the date System.out.println("Date1: " + date1); DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; System.out.println(formatter.format(date1)); }}
输出
Date1: 2018-12-12T13:30:30+05:0013:30:30+05:00
程序2 :
// Java program to demonstrate the format() method// Exceptions import java.time.OffsetDateTime;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { try { // Parses the date1 OffsetDateTime date1 = OffsetDateTime.parse("2018-13-12T13:30:30+05:00"); // Prints the date System.out.println("Date1: " + date1); DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; System.out.println(formatter.format(date1)); } catch (Exception e) { System.out.println(e); } }}输出
java.time.format.DateTimeParseException: Text '2018-13-12T13:30:30+05:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 13
参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html#format-java.time.format.DateTimeFormatter-
