Anuja
Anuja

Reputation: 419

Java DateFormat conversion automatically increases hour by 1

I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.

My Code:

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
}

format string: ddMMMyyyy / hh:mm z

Input Date: 07DEC2015 / 10:02 GMT

Output Date: 07/12/2015 11:02:00

Upvotes: 1

Views: 1385

Answers (2)

jmathewt
jmathewt

Reputation: 947

If you don't want to use timezone, in java 8 you can use 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
*/

Upvotes: 1

Anuja
Anuja

Reputation: 419

outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

resolved it.

Upvotes: 1

Related Questions