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

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

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

Java中 OffsetTime 类的format()方法使用函数参数中传递的指定格式化程序来格式化这次时间。

句法:

public String format(DateTimeFormatter formatter)

参数:此方法接受一个强制参数格式化程序,它指定要使用的格式化程序,它不为空。

返回值:返回格式化的日期字符串,不为空。

异常:当打印过程中发生错误时,该函数返回由方法抛出的DateTimeException

下面的程序说明了format()方法:

程序 1:

// Java program to demonstrate the format() method
  
import java.time.OffsetTime;
import java.time.format.DateTimeFormatter;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Parses the given time
        OffsetTime time
            = OffsetTime.parse("15:45:35+06:02");
  
        // Prints the parsed time
        System.out.println("Time: "
                           + time);
  
        // Function used
        DateTimeFormatter formatter
            = DateTimeFormatter.ISO_TIME;
  
        // Prints the formatted time
        System.out.println("Formatted time: "
                           + formatter.format(time));
    }
}
输出:
Time: 15:45:35+06:02
Formatted time: 15:45:35+06:02

方案二

// Java program to demonstrate the format() method
  
import java.time.OffsetTime;
import java.time.format.DateTimeFormatter;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Parses the given time
        OffsetTime time
            = OffsetTime.parse("11:14:13+07:05");
  
        // Prints the parsed time
        System.out.println("Time: "
                           + time);
  
        // Function used
        DateTimeFormatter formatter
            = DateTimeFormatter.ISO_TIME;
  
        // Prints the formatted time
        System.out.println("Formatted time: "
                           + formatter.format(time));
    }
}
输出:
Time: 11:14:13+07:05
Formatted time: 11:14:13+07:05

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