sxwz2.0/src/main/java/com/kexue/skills/common/util/DateConverter.java
2026-01-22 10:20:02 +08:00

91 lines
3.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.kexue.skills.common.util;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import java.util.Date;
/**
* @author 维哥
* @Description
* @create 2025-03-03 10:58
*/
public class DateConverter {
/**
* 将中文日期格式转换为标准格式yyyy-MM-dd
* @param chineseDate 示例:"2025年2月22日"
* @return 示例:"2025-02-22"
*/
public static String convertChineseDate(String chineseDate) {
if (StrUtil.isBlank(chineseDate)) return null;
return DateUtil.parse(chineseDate.replace("", ""), "yyyy年M月d")
.toString("yyyy-MM-dd");
}
/**
* 将简写时间转换为标准时间格式HH:mm:ss
* @param shortTime 示例:"1:30" 或 "12:5"
* @return 示例:"01:30:00" 或 "12:05:00"
*/
public static String convertShortTime(String shortTime) {
if (StrUtil.isBlank(shortTime)) return null;
// 处理缺失前导零的情况
String[] parts = shortTime.split(":");
if (parts.length != 2) return null;
String hours = String.format("%02d", Integer.parseInt(parts[0]));
String minutes = String.format("%02d", Integer.parseInt(parts[1]));
return DateUtil.parseTime(hours + ":" + minutes + ":00").toString("HH:mm:ss");
}
public static Date convertChineseDateTime(String chineseDate, String shortTime){
Date date = null;
try {
// 清洗非法null字符串
if(chineseDate != null) {
chineseDate.replace(" ","");
chineseDate = chineseDate.replace(" null", ""); // 替换时间部分的null
chineseDate = chineseDate.replace("null", ""); // 处理其他可能的null情况
chineseDate = convertChineseDate(chineseDate);
}
if(shortTime != null) {
shortTime.replace(" ","");
shortTime = shortTime.replace(" null", ""); // 替换时间部分的null
shortTime = shortTime.replace("null", ""); // 处理其他可能的null情况
shortTime = convertShortTime(shortTime);
}
if (StrUtil.isNotBlank(chineseDate) && StrUtil.isNotBlank(shortTime)){
date = DateUtil.parse(chineseDate+ " " + convertShortTime(shortTime)==null?"00:00:00":convertShortTime(shortTime));
}
if (StrUtil.isNotBlank(chineseDate) && StrUtil.isBlank(shortTime)){
return DateUtil.parse(chineseDate);
}
} catch (Exception e) {
e.printStackTrace();//
}
date = DateUtil.parse(chineseDate + " 00:00:00");
return date;
}
public static String convertChineseDateTimeStr(String chineseDate, String shortTime){
if (StrUtil.isNotBlank(chineseDate) || StrUtil.isNotBlank(shortTime)){
return convertChineseDate(chineseDate)+ " " + convertShortTime(shortTime);
}
return "";
}
// 测试示例
public static void main(String[] args) {
System.out.println(convertChineseDate("2025年2月22日")); // 输出2025-02-22
System.out.println(convertShortTime("1:30")); // 输出01:30:00
System.out.println(convertShortTime("12:5")); // 输出12:05:00
}
}