PHP - Short hand if statement with a date format with weird output
I am using a short hand notation of an if statement to format a field. If the field is an empty string I leave it as an empty string, if not then I am trying to format it to a proper datetime format so it can be inserted into a mysql db. here is my php code
$date = ($date == '') ? date("Y-m-d", strtotime($date)) : $date;
for some reason when the $date string is not empty it is returning it int he format 'm/d/Y' example: 04/01/2010
When I pull the code out of the shorthand if
$date = date("Y-m-d", strtotime($date));
print($date);
it is formatted correctly like this 'Y-m-d' or 2010-04-01开发者_运维知识库. Does anyone know why this happens? Thanks
I'm taking a bit of a stab in the dark here at what you were trying to accomplish, but you might have more luck with this:
$date = ($ts = strtotime($date)) ? date("Y-m-d", $ts) : '';
This will attempt to parse any incoming date string, and fail to an empty string if the date was unparsable.
Note that it's important to do a check on strtotime's ability to parse a date, because date("Y-m-d", strtotime($date)) will return a date somewhere around 1970 if $date doesn't contain a parsable date.
e.g.:
$ php -r 'var_dump(date("Y-m-d", strtotime("thisisnotadate")));'
string(10) "1970-01-01"
$ php -r 'var_dump(date("Y-m-d", strtotime("01/01/1901")));'
string(10) "1970-01-01"
$ php -r 'var_dump(date("Y-m-d", strtotime("01/01/2048")));'
string(10) "1970-01-01"
$
strtotime can only handle dates that fit in a 32 bit timestamp, which limits it to 1970 - 2038. Additionally, some date formats may be ambiguous.
you confused the arguments of your ternary operator, just switch them, or change the equality operator to check for inequality:
$date = ($date !== '') ? date("Y-m-d", strtotime($date)) : $date;
In the case you describe, $date
must have already been set elsewhere in the script using the m/d/Y
notation. In that case, the ternary operator leves $date
untouched.
When you get rid of the shorthand, that m/d/Y
string is being forced into a timestamp by strtotime
, and then into a proper Y-m-d
string by date()
.
Right now, your statement is:
If $date is an empty string, pass that empty string as a timestamp to the string to time function. Pass that to the date function. Otherwise return the contents of $date.
Perhaps you intend:
$date = ($date == '') ? date("Y-m-d") : $date;
Seems to me you're doing something you don't need to (using ternary syntax). From one of your comments My intention is that if it is an empty string then keep it an empty string, if not then formate it using strtotime then the date function. I would need the strtotime in there to properly format it for mysql
if($date != '') // leave it alone if it is an empty string
{
$date = date("Y-m-d", strtotime($date));
}
(Important note - I haven't touched PHP for years, so syntax may be off, but the principle is the same)
精彩评论