开发者

PHP date format - Im about ready to break something [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. I开发者_开发技巧f you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 11 years ago.

I've got a standard "US" way of expressing a date - 06/29/1967 or 6-29-67

strtotime() and create_date() and date() or date_format() ALL choke on this.

the db is MySQl - storing a date as yyyy-mm-dd.

Unfortunately, I can't change my schema to store my dates as epoch time stamps or integers.


This will convert your standard date to the format your database requires.

date('Y-m-d', strtotime('06/29/1967'));


I'm not sure if I understand your problem well, but you can use a combination of date and mktime functions, like that:

echo date('Y-m-d', mktime(0, 0, 0, month, day, year));

http://php.net/manual/en/function.mktime.php


This is what I've been doing with my PHP/MySQL setup:

Create a date object:
$date = new DateTime(null, new DateTimeZone("UTC"));

Save date in DB:
$dateString = $date->format("Y-m-d H:i:s");

Retrieve date from DB:
$retrievedDateString = $retrievedDate = new DateTime($retrievedDateString, new DateTimeZone("UTC"))


Actually @Ramy Deeb replied the same thing I was going to, strtotime will convert into a UNIX timestamp almost anything you throw at it, and date will just make it what you need.

To check what strtotime can handle you can check the date formats for strtotime or the full documentation for acceptable formats


Well you can use date_create_from_format for this as follows:

$myDate = date_create_from_format('m/d/Y', '06/29/1967');

For 2 digit format the following is the format,

$myDate2 = date_create_from_format('n-d-y', '6-29-67');

NOTE: The above date is interpreted as 29th June 2067 NOT 29th June 1967 because oh PHP's interpretation of 2 digit years. I have tested and PHP treats years from:

70 - 99   =>  1970 - 1999
00 - 69   =>  2000 - 2069

Thus i recommend using four digit year format.
But if you cannot change the data source, then for a date like yours where 69 is 1969, I would convert the year afterwards as per my own condition, like this:

// if the date is wrongly interpreted as 2000+, change it to 1900 one
// here I have choosen range '38 - 99' as '1938 - 1999' 
if(date_format($myDate2, 'Y') > 2038)
    date_sub($myDate2, date_interval_create_from_date_string('100 years'));

After you have gotten the $myDate object with the correct date use date_format

$db_date_str = date_format($myDate, 'Y-m-d');

And insert this into DB.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜