简体   繁体   English

PHP和mySQL:日期和时间存储

[英]PHP & mySQL : Date + Time Storage

I've been reading about storing and displaying dates and times in mySQL, but I don't seem to find an answer that suits my needs or I'm incapable of coding my own one. 我一直在阅读有关在mySQL中存储和显示日期和时间的信息,但似乎找不到适合我需求的答案,或者我无法编写自己的答案。 I guess being full of doubts doesn't help at all. 我想充满怀疑根本没有帮助。

The thing is, I have a mySQL table with a field (text) which I would like to contain certain times and dates. 问题是,我有一个带字段(文本)的mySQL表,我想包含某些时间和日期。 At the moment I'm working with "d/m/YH:i" format, but I'm pretty sure that's not neat. 目前,我正在使用“ d / m / YH:i”格式,但是我敢肯定那不是很整齐。 I'm using that format because it's the format I want it to be displayed on the site. 我正在使用该格式,因为它是我希望在网站上显示的格式。

Could anyone tell me what the correct way of handling this issue would be? 谁能告诉我解决此问题的正确方法是什么? Maybe I have to store the date and time in another format and convert it when it's going to be be displayed on the site. 也许我必须以其他格式存储日期和时间,并在将其显示在网站上时进行转换。

You should store them as TIMESTAMP or DATETIME (check the differences here ) 您应该将它们存储为TIMESTAMP或DATETIME(在此处检查差异)

and then convert them when you write or read the values, for example: 然后在写入或读取值时将其转换,例如:

INSERT INTO table (date_time) VALUES (CURRENT_TIMESTAMP)

SELECT date_format(date_time, '%b %d %Y %h:%i %p') as date_time FROM table ...

i would say your guess would be the best way to do it. 我会说你的猜测将是最好的方法。 Store it in seconds since EPOCH and then convert using any multitude of ways that php offers: 自EPOCH以来,将其存储在几秒钟内,然后使用php提供的多种方法进行转换:

take a look at this: 看看这个:

epoch time stamp 时代时间戳记

the epoch time stamp is valid for ANY time zone. 纪元时间戳在任何时区均有效。 Which makes your server location not important. 这使您的服务器位置不重要。 You could show time for any time zone as long as your parse it correctly with php (or you could even do it client-side with JS) 您可以显示任何时区的时间,只要使用php正确解析即可(或者甚至可以使用JS在客户端进行)

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

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