在Java中处理字符数组表示的TransactionTime
(例如["2025-06-01","2025-06-10"]
),将其转换为开始时间和结束时间,推荐使用Java 8+的java.time
API(如LocalDate
)。以下是完整代码示例:
解决方案代码
java
复制
下载
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException;public class TransactionTimeParser {public static void main(String[] args) {// 示例输入数据String[] transactionTime = {"2025-06-01", "2025-06-10"};try {// 1. 解析开始时间LocalDate startDate = parseDate(transactionTime[0]);// 2. 解析结束时间LocalDate endDate = parseDate(transactionTime[1]);// 3. 输出结果(或进行后续业务操作)System.out.println("开始时间: " + startDate);System.out.println("结束时间: " + endDate);// 示例:计算时间跨度long daysBetween = java.time.temporal.ChronoUnit.DAYS.between(startDate, endDate);System.out.println("时间跨度: " + daysBetween + " 天");} catch (DateTimeParseException e) {System.err.println("日期格式错误: " + e.getMessage());} catch (ArrayIndexOutOfBoundsException e) {System.err.println("数组长度不足: 需要2个日期元素");}}private static LocalDate parseDate(String dateStr) throws DateTimeParseException {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");return LocalDate.parse(dateStr, formatter);} }
关键步骤解析:
-
数据验证
-
确保数组长度至少为2(避免
ArrayIndexOutOfBoundsException
)。 -
检查日期格式是否符合
yyyy-MM-dd
(如2025-06-01
)。
-
-
日期解析
-
使用
DateTimeFormatter
定义格式("yyyy-MM-dd"
)。 -
通过
LocalDate.parse()
将字符串转换为LocalDate
对象。
-
-
异常处理
-
DateTimeParseException
:日期格式无效时抛出(如2025/06/01
)。 -
ArrayIndexOutOfBoundsException
:数组元素不足时抛出。
-
-
后续操作
-
可直接使用
LocalDate
对象进行日期计算(如计算时间跨度、日期比较等)。
-
执行结果:
text
复制
下载
开始时间: 2025-06-01 结束时间: 2025-06-10 时间跨度: 9 天
注意事项:
-
时区问题
LocalDate
不包含时区信息,如需时区支持请改用ZonedDateTime
。 -
空值检查
实际业务中应增加对transactionTime
为null
或空数组的判断。 -
日期逻辑
如果结束时间早于开始时间,需根据业务需求处理(如抛出异常或交换值)。
推荐使用
LocalDate
的优势:
不可变且线程安全
提供丰富的日期计算方法(如
plusDays()
、isBefore()
等)避免遗留
Date
和Calendar
类的设计缺陷
转换为 LocalDateTime
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;public class TransactionTimeParser {public static void main(String[] args) {// 示例输入数据String[] transactionTime = {"2025-06-01", "2025-06-10"};try {// 1. 解析开始时间(转换为当天的00:00:00)LocalDateTime startDateTime = parseStartDateTime(transactionTime[0]);// 2. 解析结束时间(转换为当天的23:59:59.999999999)LocalDateTime endDateTime = parseEndDateTime(transactionTime[1]);// 3. 输出结果System.out.println("开始时间: " + startDateTime);System.out.println("结束时间: " + endDateTime);// 示例:计算时间跨度(以天为单位)long daysBetween = java.time.temporal.ChronoUnit.DAYS.between(startDateTime.toLocalDate(), endDateTime.toLocalDate());System.out.println("时间跨度: " + daysBetween + " 天");} catch (DateTimeParseException e) {System.err.println("日期格式错误: " + e.getMessage());} catch (ArrayIndexOutOfBoundsException e) {System.err.println("数组长度不足: 需要2个日期元素");}}// 解析为开始时间(当天的00:00:00)private static LocalDateTime parseStartDateTime(String dateStr) {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");LocalDate date = LocalDate.parse(dateStr, formatter);return date.atStartOfDay(); // 转换为当天的开始时间}// 解析为结束时间(当天的最后一刻)private static LocalDateTime parseEndDateTime(String dateStr) {DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");LocalDate date = LocalDate.parse(dateStr, formatter);return date.atTime(LocalTime.MAX); // 23:59:59.999999999}
}
// 查询试剂交易(入库/出库)记录@Overridepublic List<BranchWarehouseTransactions> queryForReagent(BranchWarehouseTransactionsQueryDTO queryDTO) {if ((queryDTO.getTransactionTime() == null || queryDTO.getTransactionTime().isEmpty()) &&queryDTO.getTransactionType() == null &&(queryDTO.getMaterialName() == null || queryDTO.getMaterialName().isEmpty())) {throw new RuntimeException("请输入查询条件!");}// 处理字符日期数组,数据格式为:["2025-06-01","2025-06-10"],需处理为 LocalDateTime 格式的开始时间和结束时间// 日期格式器DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");// 1. 解析开始时间String beginDateStr = null;LocalDateTime beginDateTime = null;if (queryDTO.getTransactionTime() != null && queryDTO.getTransactionTime().size() == 2) {beginDateStr = queryDTO.getTransactionTime().get(0);}if (beginDateStr != null && !beginDateStr.isEmpty()) {// 字符串 转 日期LocalDate startDate = LocalDate.parse(beginDateStr, formatter);// 日期 转 日期时间(当天的 00:00:00)beginDateTime = startDate.atStartOfDay();}queryDTO.setTransactionTimeBegin(beginDateTime);// 2. 解析结束时间String endDateStr = null;LocalDateTime endDateTime = null;if (queryDTO.getTransactionTime() != null && queryDTO.getTransactionTime().size() == 2) {endDateStr = queryDTO.getTransactionTime().get(1);}if (endDateStr != null && !endDateStr.isEmpty()) {// 字符串 转 日期LocalDate endDate = LocalDate.parse(endDateStr, formatter);// 日期 转 日期时间(当天的 23:59:59.999999999)endDateTime = endDate.atTime(LocalTime.MAX);}queryDTO.setTransactionTimeEnd(endDateTime);// 检查日期逻辑关系if (beginDateTime != null && beginDateTime.isAfter(endDateTime)) {throw new IllegalArgumentException("开始时间不能晚于结束时间!");}return branchWarehouseMapper.selectForReagent(queryDTO);}