Format a date in PHP

$Date = "040312"; //mmddyy

I want the date to be formatted as such: 4/3/2012, how can I do that?
LVL 3
Computer GuyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Olaf DoschkeConnect With a Mentor Software DeveloperCommented:
What version of php are you using?

DateTime::createFromFormat()  exists since version 5.3.0

Bye, Olaf.
0
 
Olaf DoschkeSoftware DeveloperCommented:
<?php
$Date = '040312';
$DateTimeObject = DateTime::createFromFormat('mdy', $Date);
echo $DateTimeObject->format('n/j/Y');
?>

Open in new window

Bye, Olaf.
0
 
Computer GuyAuthor Commented:
Hi,

Thanks, but I got this error:

Fatal error: Call to undefined method DateTime::createFromFormat() in /home/test/public_html/datetest.php on line 3
0
Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

 
Ray PaseurCommented:
0
 
Ray PaseurConnect With a Mentor Commented:
See http://www.laprbass.com/RAY_temp_audiotech.php
<?php // RAY_temp_audiotech.php
error_reporting(E_ALL);
echo "<pre>";

date_default_timezone_set('America/Chicago');

// NEVER STORE A DATE IN THIS FORMAT - USE ISO-8601 INSTEAD
$date = '040312';

// REFORMAT THE DATE
$new
= substr($date,0,2)
. '/'
. substr($date,2,2)
. '/'
. substr($date,4,2)
;
echo $new;
echo PHP_EOL;

// CONVERT TO ISO-8601
$iso = date('c', strtotime($new));
echo $iso;
echo PHP_EOL;

// CONVERT TO ANOTHER FORMAT
$alt = date('n/j/Y', strtotime($new));
echo $alt;
echo PHP_EOL;

Open in new window

0
 
rinfoCommented:
This can be done using following code.
$Date = "040312";
$m  =  substr($date,0,2);
$d =   substr($date,2,2);
$y =    substr($date,4,2);
$uDate  = mktime(0, 0, 0, $m, $d, $y);
$fdate   =  date("m/d/y", $udate);

However end point is what Ray has to say . Stick to convention always.
0
 
Olaf DoschkeSoftware DeveloperCommented:
I asume audiotech520 has updated PHP so my first answer works, but then that answer should be marked, not the (indirect) advice to update PHP.

It would be fair and I would not mind, if points would be shared on several answers, which also work with older PHP versions.

Bye, Olaf.
0
 
Ray PaseurCommented:
This worked when I tested it: ID: 37808833.  Not particularly worried about the points, just keeping an accurate answer set in the PAQ.
0
All Courses

From novice to tech pro — start learning today.