Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime object

Tags:

php

Why in the first example i got minutes and seconds 00:00 and in the second example, when no hour is specified, i got actual time?
I wanna always values 0 if in the date from which the object was created that value isn`t defined.

echo DateTime::createFromFormat('j.n.Y H', "3.4.2012 22")->format('Y-m-d H:i:s');

Output: 2012-04-03 22:00:00

echo DateTime::createFromFormat('j.n.Y', "3.4.2012")->format('Y-m-d H:i:s');

Output: 2012-04-03 23:05:45

Excpected output: 2012-04-03 00:00:00

like image 966
Krab Avatar asked Dec 02 '13 22:12

Krab


1 Answers

This will give your wished format:

echo DateTime::createFromFormat('!j.n.Y', "3.4.2012")->format('Y-m-d H:i:s');


Output: 2012-04-03 00:00:00
Excpected output: 2012-04-03 00:00:00

Ref: http://php.net/manual/en/datetime.createfromformat.php

! Resets all fields (year, month, day, hour, minute, second, fraction and timzone information) to the Unix Epoch Without !, all fields will be set to the current date and time.

In other words, without the exclamation mark !, if you don't specify any of H (hours), i (minutes), and s (seconds), the current OS system time running the PHP script is used.

If any of the elements H, i, or s are given, the system time is not used. In effect, 0 will fill all unspecified time elements. For example:

echo DateTime::createFromFormat('j.n.Y H', "3.4.2012 22")->format('Y-m-d H:i:s');
//=> 2012-04-03 22:00:00

echo DateTime::createFromFormat('j.n.Y i', "3.4.2012 22")->format('Y-m-d H:i:s');
//=> 2012-04-03 00:22:00

echo DateTime::createFromFormat('j.n.Y s', "3.4.2012 22")->format('Y-m-d H:i:s');
//=> 2012-04-03 00:00:22
like image 62
jacouh Avatar answered Sep 23 '22 08:09

jacouh