java.util.Date
类型。 ,public void processDate(Date inputDate) { ... }
,调用时可传入new Date()
表示当前时间,或new Date(long timestamp)
指定时间戳,注意处理时区与过期API问题。在Java中处理Date
参数涉及创建、传递和格式化日期对象,以下是详细指南:
创建Date对象
-
基本创建(已过时但需了解)
import java.util.Date; // 当前时间 Date currentDate = new Date(); // 指定时间戳(1970年1月1日以来的毫秒数) Date specificDate = new Date(1640995200000L); // 2022-12-31 00:00:00
⚠️ 注意:
Date
的构造方法(如Date(int year, int month, int day)
)已弃用,不推荐使用。 -
通过
Calendar
创建(推荐旧版API方案)import java.util.Calendar; Calendar cal = Calendar.getInstance(); cal.set(2025, Calendar.JANUARY, 15, 10, 30); // 年月日时分 Date date = cal.getTime();
传递Date参数
在方法中直接使用Date
类型作为参数:
// 定义方法 public void processDate(Date inputDate) { System.out.println("Received: " + inputDate); } // 调用方法 Date myDate = new Date(); processDate(myDate); // 传递Date对象
格式化与解析(关键步骤)
使用SimpleDateFormat
转换日期与字符串:
import java.text.SimpleDateFormat; // 1. Date → 字符串 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = sdf.format(new Date()); // 输出如 "2025-10-05 14:30:00" // 2. 字符串 → Date String input = "2025/10/05"; SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd"); Date parsedDate = sdf2.parse(input); // 字符串转Date参数
Java 8+ 替代方案(强烈推荐)
弃用老旧的Date
,改用java.time
包(更安全、更直观):
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; // 创建日期时间 LocalDateTime now = LocalDateTime.now(); // 当前时间 LocalDateTime customDate = LocalDateTime.of(2025, 10, 5, 8, 30); // 格式化 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String formatted = customDate.format(formatter); // 解析字符串为日期 LocalDateTime parsed = LocalDateTime.parse("2025-10-05 08:30", formatter);
常见场景示例
-
HTTP请求接收Date参数
前端传递时间字符串(如JSON),后端解析:// Spring Boot示例 @PostMapping("/event") public ResponseEntity<?> createEvent(@RequestParam("eventDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date eventDate) { // 处理eventDate }
-
数据库操作
使用PreparedStatement
设置Date参数:java.sql.Date sqlDate = java.sql.Date.valueOf("2025-10-05"); // 仅日期 PreparedStatement ps = connection.prepareStatement("INSERT INTO orders VALUES (?)"); ps.setDate(1, sqlDate);
最佳实践
-
弃用警告
- 避免使用
Date
的过时构造方法(如new Date(2025, 10, 5)
)。 - 多线程环境下
SimpleDateFormat
非线程安全,需配合ThreadLocal
使用。
- 避免使用
-
升级建议
- 新项目优先使用
java.time.LocalDate
、LocalDateTime
。 - 旧系统迁移时,用
Date.from(instant)
和date.toInstant()
与新版API互转。
- 新项目优先使用
权威引用说明
- Oracle官方文档:Java 8 Date-Time API
- 《Effective Java》第3版:Item 17 推荐不可变对象(如
java.time
中的类)- OWASP安全指南:日期解析需验证输入,防止注入攻击
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/25313.html