我试图在字符串及其输入格式字符串中取日期并以输出格式转换日期。但是在转换为Date之后,java代码会将小时数增加一个。我无法理解导致错误的原因。
我的代码:
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
输入日期:07DEC2015 / 10:02 GMT
输出日期:07/12/2015 11:02:00
答案 0 :(得分:1)
outputFormat.setTimeZone(TimeZone.getTimeZone( “GMT”));
解决了它。
答案 1 :(得分:0)
如果您不想使用时区,则在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
*/