1

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 ?

shatheesh
  • 633
  • 6
  • 10
user2733521
  • 439
  • 5
  • 22

3 Answers3

5

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
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • This will only output the current date and time, not a string with date and time in it. – Oscar M. May 13 '14 at 13:52
  • I didn't assume OP asked for that? But if that's needed, that can be sent to the function – Hanky Panky May 13 '14 at 13:53
  • And rather than using 2 date formats and converting from one to another, OP would be better of fixing this date printing at the source itself, if at all it is in their control. These Modifiers remain same even for `DateTime` class – Hanky Panky May 13 '14 at 14:02
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.

Oscar M.
  • 1,076
  • 7
  • 9
0

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');
Tan Hong Tat
  • 6,671
  • 2
  • 27
  • 25