3

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.

sh3rifme
  • 1,054
  • 1
  • 11
  • 26
  • the easiest way is probably to cast your int into a string and use substr? – Pascamel Jan 29 '14 at 14:07
  • `01042012` is an octal number (equivalent to the decimal `279562`). You should look at the parameter descriptions for the [`date()` function](http://php.net/date); you cannot just throw anything into it and expect it to work. – Sverri M. Olsen Jan 29 '14 at 14:16

3 Answers3

15

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');
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • 1
    I would use this, but my university has required that we use a version of MicroApache that uses PHP 5.2 Thank you though for the help! – sh3rifme Jan 29 '14 at 14:19
5

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;
Alyas
  • 620
  • 1
  • 10
  • 22
0

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.

Michael Ford
  • 851
  • 6
  • 9
  • Numbers that [start with `0` are octal](http://php.net/integer#language.types.integer.syntax), not integer. – Sverri M. Olsen Jan 29 '14 at 14:19
  • Ahh, very good! Thanks for the correction. Still makes much more sense to use a string in this situation, but thanks for correcting/teaching me :-) – Michael Ford Jan 29 '14 at 14:23
  • Yes, a string makes more sense. Using a better format, such as a UNIX timestamp or a date/time parsable by `strtotime()`, would make *even more* sense. – Sverri M. Olsen Jan 29 '14 at 14:27