简体   繁体   中英

Why does MySql respond with a different time than is in the database?

So, from MySql workbench, the date is '2021-01-01 05:35:40', but when i fetch the date column through nodejs via the mysql npm package, I get 2021-01-01T10:52:48.000Z. The weirdest thing to me, is the local date I did created this record would've actually been 2021-01-01 00:35:40. So, the value I am getting in workbench is 5 hours ahead, and I don't even know how to read the response I am getting on my server(T and.000Z bit) but I assume that it is 10 hours ahead of my actual time, and 5 hours ahead of what I am getting from workbench.

Here's the answer. It is because you are using NodeJS or more specifically, JavaScript. Dates from MySQL get converted to ISO date strings in JS but their value remains the same.

You can use these functions to format dates from ISOdateStrings to readable formats.

module.exports.formatDate = (date) => {
    const _date = new Date(date);
    const day = _date.getDate();
    const month = _date.getMonth() + 1;
    const year = _date.getFullYear();
    return `${year}-${month}-${day}`;
}

module.exports.formatTime = (date) => {
    const _date = new Date(date);
    const hours = _date.getHours()
    const minutes = _date.getMinutes();
    const seconds = _date.getSeconds();
    return `${hours}:${minutes}:${seconds}`;
}

module.exports.toDateTimestamp = (date) => {
    const dateStamp = this.formatDate(date);
    const timeStamp = this.formatTime(date);
    return `${dateStamp} ${timeStamp}`
}

Try the following steps:

  • Restart MySql

sudo /etc/init.d/mysqld restart

Reference - https://major.io/2007/07/01/mysql-time-zone-different-from-system-time-zone/

  • my.cnf has the wrong setting for timezone, correct format is like this:

default_time_zone=Europe/Riga

Also make sure you have updated mysql timezones via shell like this: https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

using mysql_tzinfo_to_sql...

  • Probably MySql has a correct time setting already, but it's just that you're SSHing into the server I recently had to troubleshoot this exact issue, thus finding this post. In our case the dev was using an alias to connect to MySQL, and he did not remember that MySQL was actually running on a different host than he was SSHing into (also with an alias).

Try the following steps: Check timezone of server and your client end. Restart Sql service after correct Time zone.

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