Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

WangScaler: A writer with heart.

Declaration: uneducated, if there is a mistake, kindly correct.

During development, we often need to add time to the table, and when we save time to the database, it magically disappears for eight hours. What’s going on? We know from geography that Beijing time is east 8, which means we need to add eight hours to UTC time.

So are we going to add eight hours to the programming time? Of course not, we just need to change the database time to Beijing time.

Mysql

1. Set the time zone for the host

1. Change the time zone of the host

When the Mysql server starts up, it tries to determine the host’s time zone and uses it to set the system_time_zone system variable. This value does not change thereafter. So the first option is to change the host’s time zone directly.

Tzselect 4, Asia select 9, China select 1, Beijing Time select 1, YesCopy the code

Can be

2, check the host time

date
Copy the code

Check whether the current host time is correct

Change the time zone of Mysql

1, modify,

  • Temporary changes, restarts will be lost

    mysql> set time_zone = '+8:00'; 
    mysql> set global time_zone = '+8:00';
    Copy the code
  • Permanent change, change after restart

    Default-time_zone = '+8 '# mysql systemctl restart mysqldCopy the code

2. Check the Settings

Select @@global.time_zone,@@session.time_zone; show variables like '%time_zone%'; Select now();Copy the code

Modify the URL of the connection

jdbc:mysql://localhost:3306/mydemo? useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/ShanghaiCopy the code

Mongo

Mongo, on the other hand, has a very different view of time zones than Mysql. We can’t convert it to UTC every time we save it and then convert it back every time we retrieve it. I am using Motor, so taking Motor as an example, I only need to set the time zone when connecting, and it will automatically change to Beijing time.

AsyncIOMotorClient(self.motor_uri, retryWrites=False, io_loop=self.loop, tz_aware=True,
                          tzinfo=pytz.timezone('Asia/Shanghai'))
Copy the code

The last

One can plant trees, and another can enjoy the shade. One step on the pit, the next generation continue to fall, hahaha. The original you are not finished to see this article, but to finish reading this article and then step on the pit.

Come all come, click “like” and then go!

Follow WangScaler and wish you a promotion, a raise and no bucket!