I’m working with PHP 5.3 on my local machine and needed to parse a UK date format (dd/mm/yyyy). I found that strtotime
didn’t work with that date format, so I used date_create_from_format
instead – which works great.
Now, my problem is that my staging server is running PHP 5.2, and date_create_from_format
doesn’t work on that version. (It’s a shared server, and wouldn’t have a clue how to upgrade it to PHP 5.3)
So is there a similar function to date_create_from_format
that I can use? Bespoke or PHP native?
If strptime
is not available to you, then here is a different idea. It is similar to Col. Shrapnel’s approach but instead uses sscanf
to parse the date-part values into variables and uses those to construct a new DateTime
object.
list($day, $month, $year) = sscanf('12/04/2010', '%02d/%02d/%04d');
$datetime = new DateTime("$year-$month-$day");
echo $datetime->format('r');
Answer:
Try strptime()
which is available in PHP 5.1 and above.
Answer:
include this code:
function DEFINE_date_create_from_format()
{
function date_create_from_format( $dformat, $dvalue )
{
$schedule = $dvalue;
$schedule_format = str_replace(array('Y','m','d', 'H', 'i','a'),array('%Y','%m','%d', '%I', '%M', '%p' ) ,$dformat);
// %Y, %m and %d correspond to date()'s Y m and d.
// %I corresponds to H, %M to i and %p to a
$ugly = strptime($schedule, $schedule_format);
$ymd = sprintf(
// This is a format string that takes six total decimal
// arguments, then left-pads them with zeros to either
// 4 or 2 characters, as needed
'%04d-%02d-%02d %02d:%02d:%02d',
$ugly['tm_year'] + 1900, // This will be "111", so we need to add 1900.
$ugly['tm_mon'] + 1, // This will be the month minus one, so we add one.
$ugly['tm_mday'],
$ugly['tm_hour'],
$ugly['tm_min'],
$ugly['tm_sec']
);
$new_schedule = new DateTime($ymd);
return $new_schedule;
}
}
if( !function_exists("date_create_from_format") )
DEFINE_date_create_from_format();
Answer:
If you need to parse only one particular format, it’s elementary string operation.
list($d,$m,$y)=explode("/",$datestr);
Answer:
use format DD-MM-YY and timestamp, I think it will be easier for you
$date="31-11-2015";
$timestamp=strtotime($date);
$dateConvert=date('d-m-Y', $timestamp);
echo $dateConvert;
I’ve used it