6

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

3
  • 5
    When you specify part of a time it will assume zeros for the missing parts. If you provide no time it assumes the current time. Commented Dec 2, 2013 at 22:13
  • @JohnConde: hm bad behavior, ty for answer Commented Dec 2, 2013 at 22:15
  • If you wanted "2012-04-03 00:00:00" as the result, use: format('Y-m-d 00:00:00') instead. Commented Dec 2, 2013 at 22:16

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.