简体   繁体   English

在mysql数据库中存储日期和时间的最准确方法

[英]the most accurate way to store date and time in mysql database

What is the best way to store date and time in the database? 在数据库中存储日期和时间的最佳方法是什么? I tried using now() on localhost: it works, but on live server it counts far back as 8 hours ago and current timestamp does the same thing. 我尝试在localhost上使用now() :它可以工作,但在实时服务器上,它可以追溯到8个小时前,而当前时间戳也可以完成同样的事情。 What is the most accurate approach? 什么是最准确的方法?

$d="INSERT INTO `users`(`time`) VALUES (now())";

You are storing the time in the most accurate method. 您以最准确的方法存储时间。 It might not be in the correct timezone, but it is (as far as the server can tell) exactly that time when saved. 它可能不在正确的时区中,但是(就服务器所能告诉的)它是保存时的确切时间。 If the timezone is incorrect, you will have to tell MySQL which timezone is considered "local" by executing something like SET time_zone = 'YOUR_TIME_ZONE' as soon as you open the connection. 如果时区不正确,则必须在打开连接后立即执行类似SET time_zone = 'YOUR_TIME_ZONE' ,以告知MySQL哪个时区被视为“本地”。

A good trick to help with dealing with times is to make your storage layer only deal with times in UTC, and translate it to the local timezone in the presentation layer. 帮助处理时间的一个好技巧是使您的存储层仅处理UTC时间,并将其转换为表示层中的本地时区。

The only thing that you had wrong was your time zone 您唯一错的是您的时区

For example, use this : 例如,使用此:

SET time_zone = 'America/New_York'; SET time_zone ='America / New_York';

with your time zone 与您的时区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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