Java DateFormat转换会自动将小时数增加1
我正在尝试获取字符串中的日期及其输入格式字符串,并将日期转换为输出格式。但是,在转换为日期后,java代码将小时数增加了一个小时。我无法理解是什么导致了这个错误 我的代码:Java DateFormat转换会自动将小时数增加1,java,parsing,datetime,date-format,Java,Parsing,Datetime,Date Format,我正在尝试获取字符串中的日期及其输入格式字符串,并将日期转换为输出格式。但是,在转换为日期后,java代码将小时数增加了一个小时。我无法理解是什么导致了这个错误 我的代码: try { DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); DateFormat inputFormat = new SimpleDateFormat(format); Date date = input
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
格式字符串:ddMMMyyyy/hh:mm z
输入日期:2015年12月7日/10:02 GMT
输出日期:2015年12月7日11:02:00
解决了 如果不想使用时区,在java 8中可以使用LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/
你的系统时区是多少?哦,你几乎肯定想要
HH
而不是HH
。看看我在这篇文章中的答案,答案很相似:这可能是一个时区问题。我假设您位于欧洲大陆,时区比格林尼治标准时间提前1小时,对吗?您可以尝试更改outputFormat
以在末尾添加一个z
,您将得到它显示的时区,这可能会更清楚地解释问题。我无法更改输出格式。但是我在代码中添加了“outputFormat.setTimeZone(TimeZone.getTimeZone(“GMT”);”,它工作得非常好。非常感谢。hh或hh是相同的。@Anujahh
和hh
有很大不同。我建议看一下医生。