杰瑞科技汇

Java String与SQL Date如何转换?

Of course! This is a very common and important task in Java when working with databases. Let's break down how to convert between java.lang.String and java.sql.Date, covering both directions and best practices.

Key Classes

  • java.lang.String: The standard Java class for text.
  • java.sql.Date: A subclass of java.util.Date. It's used to represent a date (year, month, day) without a time component. It's specifically designed to work with JDBC to map to SQL DATE types.
  • java.text.SimpleDateFormat: The classic class for parsing and formatting dates. It's flexible but not thread-safe.
  • java.time package (Java 8+): The modern, preferred API for date and time. It's immutable, thread-safe, and much easier to use. We'll cover both the old and new ways.

Converting String to java.sql.Date

This is the most common scenario, for example, when you get a date from a user via a form and need to insert it into the database.

Method 1: Using SimpleDateFormat (Legacy Approach)

This approach is common in older Java codebases (pre-Java 8).

Steps:

  1. Create a SimpleDateFormat object with the pattern that matches your input string.
  2. Use the parse() method to convert the String to a java.util.Date.
  3. Create a java.sql.Date object from the java.util.Date object.

Example:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.sql.Date;
import java.util.Date;
public class StringToSqlDateLegacy {
    public static void main(String[] args) {
        String dateString = "2025-10-27"; // Format: YYYY-MM-DD
        // 1. Define the date format of the input string
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 2. Parse the string to a java.util.Date
            java.util.Date utilDate = sdf.parse(dateString);
            // 3. Convert java.util.Date to java.sql.Date
            // The constructor java.sql.Date(long) takes milliseconds since epoch.
            sqlDate = new java.sql.Date(utilDate.getTime());
            System.out.println("Original String: " + dateString);
            System.out.println("Converted java.sql.Date: " + sqlDate);
            System.out.println("toString() of sql.Date: " + sqlDate.toString()); // Prints in YYYY-MM-DD format
        } catch (ParseException e) {
            System.err.println("Error parsing date string: " + e.getMessage());
        }
    }
}

Method 2: Using java.time (Modern & Recommended Approach)

Since Java 8, the java.time package is the standard for all date-time work. It's more robust and less error-prone.

Java String与SQL Date如何转换?-图1

Steps:

  1. Parse the String into a java.time.LocalDate using DateTimeFormatter.
  2. Convert the LocalDate to a java.sql.Date using the static valueOf() method.

Example:

import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class StringToSqlDateModern {
    public static void main(String[] args) {
        String dateString = "2025-10-27";
        // 1. Define the date format of the input string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        try {
            // 2. Parse the string to a LocalDate
            LocalDate localDate = LocalDate.parse(dateString, formatter);
            // 3. Convert LocalDate to java.sql.Date
            // The valueOf() method is a direct and clean conversion.
            sqlDate = Date.valueOf(localDate);
            System.out.println("Original String: " + dateString);
            System.out.println("Converted java.sql.Date: " + sqlDate);
            System.out.println("toString() of sql.Date: " + sqlDate.toString());
        } catch (Exception e) {
            System.err.println("Error parsing date string: " + e.getMessage());
        }
    }
}

Converting java.sql.Date to String

This is useful for displaying a date from the database to the user.

Java String与SQL Date如何转换?-图2

Method 1: Using SimpleDateFormat (Legacy Approach)

Steps:

  1. Create a SimpleDateFormat object with your desired output pattern.
  2. Use the format() method to convert the java.sql.Date to a String.

Example:

import java.text.SimpleDateFormat;
import java.sql.Date;
public class SqlDateToStringLegacy {
    public static void main(String[] args) {
        // Create a java.sql.Date object (e.g., from a database)
        java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
        // 1. Define the desired output format
        SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy");
        // 2. Format the java.sql.Date to a String
        String formattedString = sdf.format(sqlDate);
        System.out.println("Original java.sql.Date: " + sqlDate);
        System.out.println("Formatted String: " + formattedString);
    }
}

Method 2: Using java.time (Modern & Recommended Approach)

Steps:

Java String与SQL Date如何转换?-图3

  1. Convert the java.sql.Date to a java.time.LocalDate using toLocalDate().
  2. Format the LocalDate into a String using DateTimeFormatter.

Example:

import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SqlDateToStringModern {
    public static void main(String[] args) {
        // Create a java.sql.Date object (e.g., from a database)
        java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
        // 1. Convert java.sql.Date to LocalDate
        LocalDate localDate = sqlDate.toLocalDate();
        // 2. Define the desired output format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
        // 3. Format the LocalDate to a String
        String formattedString = localDate.format(formatter);
        System.out.println("Original java.sql.Date: " + sqlDate);
        System.out.println("Formatted String: " + formattedString);
    }
}

Summary & Best Practices

Task Legacy (SimpleDateFormat) Modern (java.time) Recommendation
Stringjava.sql.Date parse() to util.Date, then new sqlDate(utilDate.getTime()) LocalDate.parse() then Date.valueOf(localDate) Use java.time. It's clearer, safer, and the standard for new projects.
java.sql.DateString new SimpleDateFormat().format(sqlDate) sqlDate.toLocalDate().format(formatter) Use java.time. The conversion is more direct and intuitive.

Why java.time is Better:

  1. Immutability: java.time objects are immutable, making them inherently thread-safe. SimpleDateFormat is mutable and not thread-safe, which can cause subtle bugs in multi-threaded applications.
  2. Clarity: The API is much clearer. LocalDate represents just a date, which is exactly what a SQL DATE is. java.util.Date is confusing as it often includes a time component you don't want.
  3. Rich API: It provides a much richer set of methods for date manipulation (e.g., adding days, finding the difference between dates).
  4. Official Standard: It's the official JSR-310 standard and is part of Java 8 and later.

JDBC Note: java.sql.Date vs. java.time.LocalDate

When using JDBC 4.2 (Java 8+) with a modern database driver, you can often use LocalDate directly with PreparedStatement and ResultSet, avoiding the java.sql.Date wrapper altogether. This is often the cleanest approach.

Example (JDBC 4.2+):

// Inserting
LocalDate localDate = LocalDate.now();
try (PreparedStatement pstmt = connection.prepareStatement("INSERT INTO my_table (my_date) VALUES (?)")) {
    pstmt.setObject(1, localDate); // setObject with LocalDate
    pstmt.executeUpdate();
}
// Retrieving
try (ResultSet rs = statement.executeQuery("SELECT my_date FROM my_table")) {
    if (rs.next()) {
        LocalDate dateFromDb = rs.getObject("my_date", LocalDate.class);
        System.out.println("Date from DB: " + dateFromDb);
    }
}

分享:
扫描分享到社交APP
上一篇
下一篇