h.jim
h.jim

Reputation: 31

new DateTime('2016-04-01 00:00:00') returns '2016-04-01 12:00:00

This is probably a no-brainer, but I can't see the solution. I have the following code:

$begin = new DateTime('2016-03-14 00:00:00');
echo $begin->format('Y-m-d h:i:s');

The output is:

2016-03-14 12:00:00

I have tried to change timezones, set the timezone, leave it off. The output never changes. What gives? I want the output to read "2016-03-14 00:00:00".

Upvotes: 3

Views: 330

Answers (4)

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

h is for 12-hour clock (AM/PM), so your pattern lacks a or A to be complete:

$begin = new DateTime('2016-03-14 00:00:00');
echo $begin->format('Y-m-d H:i:s a');

would give you 2016-04-01 12:00:00 am.

If you want full 24-hrs clock, you need to use H instead:

$begin = new DateTime('2016-03-14 00:00:00');
echo $begin->format('Y-m-d H:i:s');

which would give expected 2016-04-01 00:00:00.

Here is the documentation for supported placeholders you can use with format().

Upvotes: 3

SamyQc
SamyQc

Reputation: 365

As said, h is for 12-hour clock format , and H for 24-hour clock format. By changing this letter, your date will format as you wish.

$begin = new DateTime('2016-03-14 00:00:00');
echo $begin->format('Y-m-d H:i:s');

Here's a list of format that you can use for DateTime object in PHP (Source)

Day of Month
____________
d   | Numeric, with leading zeros   01–31
j   | Numeric, without leading zeros    1–31
S   | The English suffix for the day of the month   st, nd or th in the 1st, 2nd or 15th.

Weekday
_______
l   | Full name  (lowercase 'L')    Sunday – Saturday
D   | Three letter name Mon – Sun

Month
______
m   | Numeric, with leading zeros   01–12
n   | Numeric, without leading zeros    1–12
F   | Textual full  January – December
M   | Textual three letters Jan - Dec

Year
____
Y   | Numeric, 4 digits Eg., 1999, 2003
y   | Numeric, 2 digits Eg., 99, 03

Time
____
a   | Lowercase am, pm
A   | Uppercase AM, PM
g   | Hour, 12-hour, without leading zeros  1–12
h   | Hour, 12-hour, with leading zeros 01–12
G   | Hour, 24-hour, without leading zeros  0-23
H   | Hour, 24-hour, with leading zeros 00-23
i   | Minutes, with leading zeros   00-59
s   | Seconds, with leading zeros   00-59
T   | Timezone abbreviation Eg., EST, MDT ...
Full Date/Time
c   | ISO 8601  2004-02-12T15:19:21+00:00
r   | RFC 2822  Thu, 21 Dec 2000 16:01:07 +0200

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

You need to use H as it is for 24 hour time and h is 12 hour time. 12:00:00 is 12am or 00:00:00:

$begin = new DateTime('2016-03-14 00:00:00');
echo $begin->format('Y-m-d H:i:s');

Upvotes: 4

JimL
JimL

Reputation: 2541

It should be

$begin = new DateTime('2016-03-14 00:00:00');
echo $begin->format('Y-m-d H:i:s');

h 12-hour format of an hour with leading zeros 01 through 12

H 24-hour format of an hour with leading zeros 00 through 23

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

Upvotes: 3

Related Questions