简体   繁体   中英

Hibernate query returning wrong date

When i retrieve a date from a mysql table it always return the date 1 day before, the date format is yyyy-MM-dd, so if i have 2018-10-17 when i print the result it comes as 2018-10-16. If i use the command line to check the dates, they are correct. This is the method inside the Dao class that retrieves the dates:

public List<LocalDate> getDates(String username){
    List<LocalDate> dates;
    Query query = manager.createQuery("select date from Calendar where username =:username");
    query.setParameter("username",username);
    dates = query.getResultList();
    return dates;
}

When I print the list all the dates are printed 1 day before as I was on my sql.

This is how I get the dates on the servlet and use hibernate to store the dates on mysql.

String dateString = request.getParameter("date");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dataInicial = LocalDate.parse(dataInicialString, formatter);

The Datatype that im using in mysql is DATE. Then I user hibernate to do the rest for me, if you need any piece of code that I didin't provide please ask me. Thx in advance.

Sorry for bad english!

i found what needed to be done, i changed the HQL query, i dont know exactly why but when i do

Query query = manager.createQuery("select DATE_FORMAT(date,'%Y-%m-%d') from Calendar where username =:username");

it works!!!!

I once had this issue and the reason resided in the default time zone of my MySQL configuration. So, first check out the time zone you are using with the following query.

SELECT @@global.time_zone;

If it is not the desired time zone, try going into your MySQL configuration file and add the following line.

[mysqld]
default-time-zone = '00:00'

Remember to set it to the desired time zone. You will need to restart your MySQL for the change to take place. This change will be permanent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM