Localdatetime advancing two hours when submitting form

Asked

Viewed 308 times

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-

  • 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 and LocalDateTime 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

  • 1

    @Valdeirpsr SHORT_IDS.get("BET") is a shortcut to America/Sao_Paulo. Only that this value is a String, and now gets a ZoneId, then the right thing would be LocalDateTime.now(ZoneId.of("America/Sao_Paulo")) (despite LocalDateTime.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 Truth. Thanks for the fix. I believe the code is on another server (maybe a virtual machine), so the difference.

No answers

Browser other questions tagged

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