Fish
Fish

Reputation: 23

PHP DateTime parsing time instead of date

I am trying to prepare a MySQL query in PHP. My problem is PHP treats dates differently to MySQL.

In MySQL '2000' is the year 2000, in PHP it's 8 PM.

$date1 = new DateTime('2000-01-01');
echo $date1->format("Y-m-d H:i:s"); // 2000-01-01 00:00:00
$date2 = new DateTime('2000-01');
echo $date2->format("Y-m-d H:i:s"); // 2000-01-01 00:00:00

// This gets 8 PM instead of the year 2000
$date3 = new DateTime('2000');
echo $date3->format("Y-m-d H:i:s"); // 2014-07-14 20:00:00

$date4 = DateTime::createFromFormat("Y-m-d H:i:s", '2000');
echo $date4->format("Y-m-d H:i:s"); // PHP Fatal error:  Call to a member function format() on a non-object

I only want the time to be parsed if it is included after the date.

Is there a way to tell it to prioritize parsing the year over the time in PHP?

Upvotes: 2

Views: 116

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173532

You can't expect DateTime to parse a date in a particular format if you're only going to pass a year.

However, you can clear all the other date fields by passing an exclamation point as part of the format:

$date = DateTime::createFromFormat('!Y', '2000');
echo $date->format('r'); // Sat, 01 Jan 2000 00:00:00: +0000

Upvotes: 2

Deele
Deele

Reputation: 3684

PHP DateTime construct first parameter is a date/time string. Valid formats are explained in Date and Time Formats. For your case, those will be Compound Formats.

You should not just toss around strings formatted in whatever way possible. You/developer is the only one who knows precisely in what format input date will be and that means, developer is responsible to sanitize/validate data required for input in DateTime class, beforehand.

tl;dr No, there is no way to prioritize parsing built inside DateTime class. You do that with your own code.

Upvotes: 0

Related Questions