在PHP,MySQL等管理日期的最佳方式是什么? [英] What's the best way to manage dates across PHP, MySQL, etc?

查看:180
本文介绍了在PHP,MySQL等管理日期的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器位于达拉斯。我在纽约市,PHP和MySQL都有配置变量来设置时区。



我如何让他们共同合作?我应该在MySQL中存储什么日期?请问如何让PHP根据用户的偏好来更改日期?



请记住:我不认为我有PHP明确设置日期,它总是在查询中使用NOW()。但我预计需要这样做。如何做?



我希望SO的经验可以帮助我。

解决方案

使用Unix时间无处不在。它使用UTC,所以每个时区都是一样的。日期的方法通常会使用时区信息转换并返回,所以您将有一个正确的时间。



或者,您可以仅使用Unix时间来传输从一台计算机到另一台计算机(从DB到运行PHP的服务器或JavaScript客户端)的时间。有各种语言的功能可以转换和使用。对于MySQL,它是:

  UNIX_TIMESTAMP(date)
FROM_UNIXTIME(unix_timestamp)

这样你可以让你的时间在数据库和日志中正确格式化,但在任何地方仍然有正确的本地时间。


My server is in Dallas. I'm in New York City.. and both PHP and MySQL have configuration variables for setting the timezone.

How do I get them all to work together? What dates should I store in MySQL? How do I get PHP to handle changing the date based on the user's preference?

Bear in mind: I don't think I'm ever having PHP explicitly set the date, it's always using "NOW()" in queries.. however I foresee the need to do this. How would this be done?

I'm hoping SO's experience can help me out here.

解决方案

Use Unix Time everywhere. It's using UTC so it's the same for every timezone. Methods for dates usually convert to it and back from it using timezone information they have, so you would have yourself a correct time.

Alternatively you could use Unix Time only to transfer time from one computer to another (like from DB to your server running PHP, or to JavaScript client). There's functions to convert to it and from it in every language. For MySQL it is:

UNIX_TIMESTAMP(date)
FROM_UNIXTIME(unix_timestamp)

That way you could have your time properly formatted on the DB and in logs but still have correct local time everywhere.

这篇关于在PHP,MySQL等管理日期的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆