Converting an 8-digit integer into dd/mm/yyyy [duplicate]

旧时模样 提交于 2019-11-30 18:07:50

问题


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.


回答1:


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;



回答2:


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');



回答3:


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.



来源:https://stackoverflow.com/questions/21433419/converting-an-8-digit-integer-into-dd-mm-yyyy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!