📜  Java中的 LocalTime parse() 方法及示例

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

Java中的 LocalTime parse() 方法及示例

在 LocalTime 类中,根据传递给它的参数,有两种类型的 parse() 方法。

解析(字符序列文本)

LocalTime类的parse()方法,用于从作为参数传递的字符串(例如 '10:15:45')中获取 LocalTime 的实例。字符串必须具有有效的日期时间,并使用 DateTimeFormatter.ISO_LOCAL_TIME 进行解析。
句法:

public static LocalTime parse(CharSequence text)

参数:此方法只接受一个参数文本,即 LocalTime 中要解析的文本。它不应该为空。
返回值:该方法返回LocalTime ,即解析后的本地日期时间。
异常:如果无法解析文本,此方法将引发DateTimeParseException
下面的程序说明了 parse() 方法:
方案一:

Java
// Java program to demonstrate
// LocalTime.parse() method
 
import java.time.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create an LocalTime object
        LocalTime lt
            = LocalTime.parse("10:15:45");
 
        // print result
        System.out.println("LocalTime : "
                           + lt);
    }
}


Java
// Java program to demonstrate
// LocalTime.parse() method
 
import java.time.*;
import java.time.format.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a formatter
        DateTimeFormatter formatter
            = DateTimeFormatter.ISO_LOCAL_TIME;
 
        // create an LocalTime object and
        LocalTime lt
            = LocalTime
                  .parse("10:15:45",
                         formatter);
 
        // print result
        System.out.println("LocalTime : "
                           + lt);
    }
}


输出:
LocalTime : 10:15:45

解析(CharSequence 文本,DateTimeFormatter 格式化程序)

LocalTime类的parse()方法,用于从使用特定格式化程序作为参数传递的字符串(例如 '10:15:45')中获取 LocalTime 的实例。使用特定格式化程序解析日期时间。
句法:

public static LocalTime parse(CharSequence text,
                              DateTimeFormatter formatter)

参数:此方法接受两个参数text是要解析的文本和formatter是要使用的格式化程序。
返回值:该方法返回LocalTime ,即解析后的本地日期时间。
异常:如果无法解析文本,此方法将引发DateTimeParseException
下面的程序说明了 parse() 方法:
方案一:

Java

// Java program to demonstrate
// LocalTime.parse() method
 
import java.time.*;
import java.time.format.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create a formatter
        DateTimeFormatter formatter
            = DateTimeFormatter.ISO_LOCAL_TIME;
 
        // create an LocalTime object and
        LocalTime lt
            = LocalTime
                  .parse("10:15:45",
                         formatter);
 
        // print result
        System.out.println("LocalTime : "
                           + lt);
    }
}
输出:
LocalTime : 10:15:45

参考:
https://docs.oracle.com/javase/10/docs/api/java Java Java )
https://docs.oracle.com/javase/10/docs/api/java Java .lang.CharSequence, Java Java)