Solution to the 8-hour slow time of unicloud cloud function

Recently, when I was working on the uniapp+unicloud applet project, everything was normal when running locally. When deployed to the cloud, I found that the time saved in the database was 8 hours slower.

After checking the information, I found out that the time zone used in unicloud cloud functions is UTC+0, and the standard Beijing time time zone should be UTC+8, so you need to pay special attention to this when using time in cloud functions. When running locally in hbuilderX, the time on the computer is used, so it will appear that everything runs normally locally, but deployment to the cloud is 8 hours slow.

The simplest solution is to directly add 8 hours to the obtained time. Of course, this method is not inherently problematic, but when tested locally, it will be 8 hours faster, so it only treats the root cause rather than the symptoms. So how to avoid this problem?

Get current time

In order to quickly develop the project, I used the moment.js time processing library in the cloud function. You can also write a function to get the time yourself. For the convenience of demonstration, I will directly use the library to introduce:

First introduce the library:

const moment = require('moment');

Use the library to get the current time:

const time = moment().format('YYYY-MM-DD HH:mm:ss');

The above method can get the current time. There is no problem locally, but the cloud will be 8 hours slower. If you use new Date() to get it, the effect is the same.

Compatible with local and cloud standard time

Use new Date().getTimezoneOffset()it to judge. If the result is 0, add 8 hours. If it is not 0, get the time normally. The getTimezoneOffset()meaning in js is that the method returns the time difference between UTC time and local time, in minutes.

Compatible use (final solution):

const time = new Date().getTimezoneOffset()==0? moment().add(8, 'hours').format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm:ss');

Summary: Instead of racking your brains and wondering why this is the case, it is better to consult more information and learn more. There will always be a solution to any problem~ Come on! ! !

Guess you like

Origin blog.csdn.net/qq_42961150/article/details/125635819