📜  Java中的 OffsetDateTime format() 方法及示例

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

Java中的 OffsetDateTime format() 方法及示例

Java中 OffsetDateTime 类的format()方法使用指定的格式化程序格式化此日期时间。

句法 :

public String format(DateTimeFormatter formatter)

参数:此方法接受单个参数格式化程序,它指定要使用的格式化程序,而不是 null。
返回值:返回格式化的日期字符串,不为空。
异常:该函数抛出一个DateTimeException ,即在打印过程中发生错误。
下面的程序说明了format()方法:
程序 1:

Java
// Java program to demonstrate the format() method
import 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));
    }
}


Java
// 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);
        }
    }
}


输出:
Date1: 2018-12-12T13:30:30+05:00
13:30:30+05:00

方案二

Java

// 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: Java/time/OffsetDateTime.html#format-java.time.format.DateTimeFormatter-