在做项目中遇到一个很奇怪的问题,将日期进行格式化的时候居然将日期减少了一天,例如,日期为04 10,2023,格式化后日期为2023-04-09,代码如下:
String tableDate = "04 10,2023";
String dateTimeFormat = "MM dd,yyyy"
Date tableDateTime = DateUtils.parseDate(tableDate, dateTimeFormat);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String tableDateTimes = format.format(tableDateTime);
/**
* 验证是否是满足格式
*
* @param inputDate 要解析的字符串
* @param format 格式
* @return 解析出来的日期,如果没有匹配的返回null
*/
public static Date parseDate(String inputDate, String format) {
if (format == null || StringUtils.isEmpty(format.trim())) {
return null;
}
try {
// 默认的市区
SimpleDateFormat df = new SimpleDateFormat(format, Locale.ENGLISH);
// 解析英文格式
SimpleDateFormat dfEn = new SimpleDateFormat(format, Locale.ENGLISH);
// 解析中文日期格式
SimpleDateFormat dfZH = new SimpleDateFormat(format, Locale.CHINESE);
ParsePosition pos = new ParsePosition(0);
// 默认
// 设置解析日期格式是否严格解析日期
// df.setLenient(false);
df.setLenient(true);
Date date = df.parse(inputDate, pos);
// 英文
dfEn.setLenient(false);
Date dateEn = dfEn.parse(inputDate, pos);
// 中文
dfZH.setLenient(false);
Date dateZh = dfZH.parse(inputDate, pos);
if (date != null) {
return date;
} else if (dateEn != null) {
return dateEn;
} else if (dateZh != null) {
return dateZh;
}
} catch (Exception e) {
LOGGER.error("解析日期错误..");
System.out.println("解析日期错误。。");
return null;
}
return null;
}
导致日期时间减少一天的原因是:可能由于时区导致日期转换不对。解决办法如下(时区可根据不同地方获取不同时区):
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
TimeZone zone = TimeZone.getTimeZone("MST");
format .setTimeZone(zone);