Wrong timezone in JAVA

Asked

Viewed 79 times

1

I’m making an application where I need to show in a graph the real time of the capture of a certain data

I tested that code:

 SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");       
 format.setTimeZone(TimeZone.getTimeZone(ZoneId.of("America/Sao_Paulo")));

But he returns to me 12:32 when in fact they are 21:32

What I’m setting wrong?

1 answer

3


According to the documentation, the lowercase letter "h" corresponds to "hour in am/pm", with values between 1 and 12 (i.e., it is an ambiguous field, which makes more sense if you also use the Pattern "a", which indicates whether the time is AM or PM).

To have hours between zero and 23, use a capital "H":

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

Even so, "hh" should return "09", which was the date used in the formatting?


Another detail is that you mixed the old API (TimeZone) with the new API (ZoneId), but there’s no need to. Or use one or the other. In this case, as you’re using the old API, don’t use ZoneId:

format.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));

But if you’re using ZoneId, means you have Java >= 8, so why not just use NEW API?

To get the current time on a particular Timezone, you can use a java.time.LocalTime, and to format, use a java.time.format.DateTimeFormatter:

// hora atual no timezone America/Sao_Paulo
LocalTime horaAtual = LocalTime.now(ZoneId.of("America/Sao_Paulo"));
// definir o formato (hora:minuto:segundo)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println(fmt.format(horaAtual));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.