当前位置: 首页 > news >正文

Java处理字符数组转换为开始日期和结束日期

在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);}
}

关键步骤解析:

  1. 数据验证

    • 确保数组长度至少为2(避免ArrayIndexOutOfBoundsException)。

    • 检查日期格式是否符合yyyy-MM-dd(如2025-06-01)。

  2. 日期解析

    • 使用DateTimeFormatter定义格式("yyyy-MM-dd")。

    • 通过LocalDate.parse()将字符串转换为LocalDate对象。

  3. 异常处理

    • DateTimeParseException:日期格式无效时抛出(如2025/06/01)。

    • ArrayIndexOutOfBoundsException:数组元素不足时抛出。

  4. 后续操作

    • 可直接使用LocalDate对象进行日期计算(如计算时间跨度、日期比较等)。

执行结果:

text

复制

下载

开始时间: 2025-06-01
结束时间: 2025-06-10
时间跨度: 9 天

注意事项:

  1. 时区问题
    LocalDate不包含时区信息,如需时区支持请改用ZonedDateTime

  2. 空值检查
    实际业务中应增加对transactionTimenull或空数组的判断。

  3. 日期逻辑
    如果结束时间早于开始时间,需根据业务需求处理(如抛出异常或交换值)。

推荐使用LocalDate的优势:

  • 不可变且线程安全

  • 提供丰富的日期计算方法(如plusDays()isBefore()等)

  • 避免遗留DateCalendar类的设计缺陷

转换为 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);}

相关文章:

  • 建设银行官方网站诚聘英才频道百度搜索量怎么查
  • 天津网站建设优化外链网盘
  • 广告设计与制作主要学什么淄博seo
  • 做网站商城需要申请商标吗济南谷歌推广
  • 前端如何兼职做网站企业网站搜索引擎推广方法
  • wordpress导航标签西安关键字优化哪家好
  • CCF GESP202503 Grade4-B4263 [GESP202503 四级] 荒地开垦
  • 自然语言处理——文本分类
  • QRadioButton(续)+ CheckBox + QLabel(2)
  • Spring Cloud微服务架构实践指南
  • 为什么要引入内联函数?
  • 71常用控件_QHBoxLayout的使用
  • OCS2库及其在足式机器人上的应用
  • 直观地理解程序的堆和栈
  • 三维图形、地理空间、激光点云渲染技术术语解析笔记
  • hot100 -- 11.二分查找系列
  • JVM内存区域与溢出异常详解
  • 算法工程师认知水平要求总结
  • 华为OD机考 - 水仙花数 Ⅰ(2025B卷 100分)
  • 数学建模期末速成 主成分分析的基本步骤
  • Z-FOLD: A Frustratingly Easy Post-Training Quantization Scheme for LLMs
  • 实战:如何用SCINet增强YOLOv8在低照度下的目标检测性能(附完整代码)
  • Linux安全加固:从攻防视角构建系统免疫
  • 打造优质技术文档指南
  • 基于RT-DETR算法的夜间交通车辆与行人目标检测
  • 附加模块--Qt OpenGL模块功能及架构