管理日期格式PHP和MySQL之间的差异 [英] Managing date formats differences between PHP and MySQL

查看:95
本文介绍了管理日期格式PHP和MySQL之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写我的第一个PHP应用程序,必须直接处理日期,因此直接处理PHP和MySQL具有不同日期格式的事实。



我的问题是:管理这种差异最优雅的方式是什么?



我有以下两个功能来使用php管理差异:

  function mysql_date($ php_date){
return date('Ymd H:i:s',$ php_date);
}

函数php_date($ mysql_date){
$ val = explode(,$ mysql_date);
$ date = explode( - ,$ val [0]);
$ time = explode(:,$ val [1]);
return mktime($ time [0],$ time [1],$ time [2],$ date [1],$ date [2],$ date [0]);
}

在我的SQL查询中是否有一个更简单的方法来直接管理? p>

或者你可以建议任何其他更优雅的方式来管理吗?

解决方案

由于(周围)PHP 5.2,PHP已经有一个内置的类/对象来处理日期和时间,称为 DateTime 。在一个空白中,使用内置函数总是比使用凌乱的细节更好。



DateTime构造函数(或date_create函数)接受日期strToTime所理解的任何格式。所有你需要知道的关于strToTime是魔术巫术,将正确地识别几乎任何字符串格式的日期。当我第一次遇到strToTime时,我有与你现在相同的内部反应(这是胡说/似乎不可靠)。不是。它的工作方式是你自己对日期的脆弱理解永远不会(如果你认为你明白日期,你不会相信我。)



所以,从MySQL中作为日期/时间字符串提取信息,并立即创建一个PHP日期对象。当/如果你需要,使用date_format方法(有一些便利常数)日期再次作为一个字符串。


I'm writing my first PHP app that has to directly deal with dates, and thus to directly deal with the fact that PHP and MySQL have different date formats.

My question is: what's the most elegant way to manage this difference?

I have the following two functions to manage the difference using php:

function mysql_date($php_date)  {
    return date( 'Y-m-d H:i:s', $php_date );
}

function php_date($mysql_date) {
    $val = explode(" ",$mysql_date);
    $date = explode("-",$val[0]);
    $time = explode(":",$val[1]);
    return mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
}

is there a simpler way to manage this directly within my SQL queries?

Or could you suggest any other more elegant way to manage this?

解决方案

Since (around) PHP 5.2, PHP has had a built in class/object for dealing with Dates and Times, called DateTime. In a void, it's always better to use a built-in than to wrangle with the messy details yourself.

The DateTime constructor (or the date_create function) accepts a date in any format understood by strToTime. All you need to know about strToTime is it's magic voodoo that will correctly recognize a date in almost any string format. When I first encountered strToTime I had the same internal reaction you're having now ("that's bullshit/seems unreliable"). It's not. It Just Works in a way that your own fragile understanding of dates never will (and if you think you understand dates, you don't. Trust Me.)

So, pull the information from MySQL as a Date/Time string, and immediately create a PHP date Object. Use the date_format method (with some handy constants) when/if you need the date again as a string.

这篇关于管理日期格式PHP和MySQL之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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