Question

So i have this function in my PHP script that is supposed to take the date as an 8-digit integer such as 01042012 and convert it to 01/04/2012 for displaying.

Currently i'm trying to use php's date() function as follows:

$int = 01042012;

$date = date("d/m/Y", $int);

Instead of $date having the value 01/04/2012 it shows as 13/01/1970.

Is this because date() wants the date i pass to it to be in unix time? If so, would there perhaps be a more direct way to split the int after characters 2 and 4 and just insert the slashes, then recombine it? Like what explode() does, but i have no character to split with.

Was it helpful?

Solution 2

An easy way to do it;

$int = 01042012;

$day = substr($int,0,2);
$month = substr($int,2,4);
$year = substr($int,4);

$date = $day.'/'.$month.'/'.$year;

OTHER TIPS

Use DateTime::createFromFormat() static method, who returns new DateTime object formatted according to the specified format:

$dt = DateTime::createFromFormat('dmY', '01042012');
echo $dt->format('d/m/Y');

Basically, you are starting off with an int value and an int value of 01042012 will really be 1042012, as the leading zero has no meaning as an int. If you started with "01042012" as a string, you would be much better starting position to accomplish you desired outcome.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top