如何在 Java 中将字符串转换为 LocalDate?

当处理用户输入的日期时,在 Java 中将字符串转换为LocalDate是一种常见操作。 Java在java.time包中提供了LocalDate类来表示没有时间信息的日期。LocalDate类是 Java 8中引入的java.time包的一部分。

java.time.LocalDate类的LocalDate.parse()方法将日期的 String 表示形式转换为LocalDate对象。 parse ()方法将采用日期字符串和 DateTimeFormatter (yyyy-MM-dd)作为参数。

定义输入格式的语法
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

将字符串日期转换为本地日期的语法
LocalDate localDate = LocalDate.parse(dateString, formatter);

示例演示了如何将 String 数据转换为 LocalDate:

// Java Program to Convert
// String to LocalDate
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

// Driver Class
public class GFG {
    
// main function 
    public static void main(String[] args)
    {
        try {
            
// Input String Date
            String dateString =
"2024-01-20";

            
// 为输入格式定义 DateTimeFormatter
            DateTimeFormatter formatter
                = DateTimeFormatter.ofPattern(
"yyyy-MM-dd");

            
// 将用户输入转换为本地日期
            LocalDate localDate
                = LocalDate.parse(dateString, formatter);

            
// Print the resulting LocalDate
            System.out.println(
"Converted LocalDate: "
                            + localDate);
        }
        catch (Exception e) {
            System.out.println(
"Error parsing the date: "
                            + e.getMessage());
        }
    }
}

上述解释:

  • 首先,我们导入了必要的类:LocalDate、DateTimeFormatter。
  • 然后,在 try-catch 块中,我们定义了一个字符串变量 dateString,其值为 yyyy-MM-dd 格式。
  • 我们使用 DateTimeFormatter.ofPattern() 方法定义了输入 dateString 的格式。
  • 通过使用 LocalDate.parse() 方法,我们将日期字符串转换为 LocalDate。
  • 转换完成后,我们将打印输出。
  • 如果在解析过程中出现异常,我们将捕获异常并打印错误信息。