1
When I will submit a form with the class Localdatetime managing the time and date fields, it advances two hours. I noticed this advance with the time of my computer.
Code:
package com.algaworks.brewer.service;
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.algaworks.brewer.model.Venda;
import com.algaworks.brewer.repository.Vendas;
@Service
public class CadastroVendaService {
@Autowired
private Vendas vendas;
@Transactional
public void salvar(Venda venda) {
if (venda.isNova()) {
venda.setDataCriacao(LocalDateTime.now());
}
if (venda.getDataEntrega() != null) {
venda.setDataHoraEntrega(LocalDateTime.of(venda.getDataEntrega(),
venda.getHorarioEntrega() != null ? venda.getHorarioEntrega() : LocalTime.now()));
}
vendas.save(venda);
}
}
Inform the
zoneId
when capturing the value. Ex.:venda.setDataCriacao(LocalDateTime.now( ZoneId.SHORT_IDS.get("BET") ));
. https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#now-java.time.Zoneid-– Valdeir Psr
The difference is between what times? Your computer with the bank, the JVM with the bank, or any other? The JVM usually uses the same spindle as the computer it is running on, but this can be changed via code and/or configuration, the same goes for the database. If you can [Edit] the question by putting some examples and printing the values of
LocalTime
andLocalDateTime
generated, in addition to the value saved in the database (which the select returns, and what Java returns when doing the query), in addition to the Timezone configured in each one (ZoneId.systemDefault()
and the bank’s Timezone), maybe you can help more– hkotsubo
@Valdeirpsr
SHORT_IDS.get("BET")
is a shortcut toAmerica/Sao_Paulo
. Only that this value is aString
, andnow
gets aZoneId
, then the right thing would beLocalDateTime.now(ZoneId.of("America/Sao_Paulo"))
(despiteLocalDateTime.now(ZoneId.of(ZoneId.SHORT_IDS.get("BET")))
also work, but I think passing "America/Sao_paulo" directly gets more succinct and less confusing). But p/me it was not clear whether the problem is exactly this (probably It’s because of Timezone, but I don’t know if that’s the only thing)– hkotsubo
@hkotsubo Truth. Thanks for the fix. I believe the code is on another server (maybe a virtual machine), so the difference.
– Valdeir Psr