Вопрос

i have a date like this :

3/6/2014 7:20

I would like it to be formatted like

03/06/2014 07:20

What is the best practice to do that ?

Это было полезно?

Решение 2

Your format is a bit ambigous, though I'm assuming since AM/PM isn't in there that the hours are in 24 hours format. Also not sure if the incoming date is day/month or month/day.

$date = new DateTime("3/6/2014 7:20");
echo $date->format('m/d/Y H:i');

Also not sure if the incoming date is day/month or month/day. But you can handle that with createFromFormat

$date = new DateTime::createFromFormat("n/j/Y G:i", "3/6/2014 7:20");
echo $date->format('m/d/Y H:i');

Read about date formats in the online docs. Also check out the DateTime book by the extension author to learn more.

Другие советы

As simple as :)

date("m/d/Y h:i");

Refer to Manual to see what these values represent. Um, let me bring those here.

m = Numeric representation of a month, with leading zeros 
d = Day of the month, 2 digits with leading zeros
Y = A full numeric representation of a year, 4 digits
h = 12-hour format of an hour with leading zeros
i = Minutes with leading zeros

Use the createFromFormat() function to read according to the specified format and output to the format you want.

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

DateTime::createFromFormat -- date_create_from_format —
Returns new DateTime object formatted according to the specified format

Example:

$date = DateTime::createFromFormat('j/n/Y', '3/6/2014 G:i');
echo $date->format('m/d/Y h:i');
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top