答案:Java中字符串与日期转换可通过Simpledateformat实现String转Date需用parse方法并处理异常,Date转String用format方法;推荐使用Java 8的DateTimeFormatter和LocalDateTime进行解析和格式化,示例展示了yyyy-MM-dd HH:mm:ss等格式的应用。

在Java中,字符串与日期之间的转换是开发中常见的需求,比如处理用户输入的时间、读取配置文件中的时间字段或格式化显示时间。下面介绍如何使用标准API完成字符串与Date类型之间的相互转换。
1. 字符串转为日期(String → Date)
将字符串转换为java.util.Date对象,需要指定字符串的日期格式,并使用SimpleDateFormat类进行解析。
步骤如下:
- 定义字符串表示的时间,如:”2024-05-20 10:30:00″
 - 创建
SimpleDateFormat对象,传入对应的格式模式 - 调用
parse()方法将字符串解析为Date对象 
注意:parse() 方法可能抛出 ParseException,必须处理异常。
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;  public class StringToDate {     public static void main(String[] args) {         String dateStr = "2024-05-20 10:30:00";         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         try {             Date date = format.parse(dateStr);             System.out.println("转换后的日期:" + date);         } catch (ParseException e) {             System.out.println("日期格式错误:" + e.getMessage());         }     } } 
2. 日期转为字符串(Date → String)
将Date对象格式化为可读的字符串,同样使用SimpleDateFormat,调用其format()方法。
示例代码:
立即学习“Java免费学习笔记(深入)”;
import java.text.SimpleDateFormat; import java.util.Date;  public class DateToString {     public static void main(String[] args) {         Date now = new Date();         SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");         String dateStr = format.format(now);         System.out.println("当前时间字符串:" + dateStr);     } } 
3. 使用 Java 8 新的时间 API(推荐)
从 Java 8 开始,引入了更强大、线程安全的java.time包,建议优先使用新API,如LocalDateTime、ZonedDateTime和DateTimeFormatter。
字符串转 LocalDateTime:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;  public class ModernStringToDate {     public static void main(String[] args) {         String dateStr = "2024-05-20 10:30:00";         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");         LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);         System.out.println("LocalDateTime:" + dateTime);     } } 
LocalDateTime 转字符串:
LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String dateStr = now.format(formatter); System.out.println("格式化结果:" + dateStr); 
常见日期格式说明
格式模式中的字母含义:
- yyyy:四位年份
 - MM:两位月份(01-12)
 - dd:两位日期(01-31)
 - HH:24小时制小时(00-23)
 - mm:分钟(00-59)
 - ss:秒(00-59)
 - hh:12小时制小时(01-12)
 - a:上午/下午标记(AM/PM)
 
  基本上就这些。新项目建议使用 Java 8 的 java.time 类型,避免旧 Date 类的诸多问题。