DateTime to string conversion and string to DateTime conversion in PHP

I’ve seen so many articles about Date and string conversion to a specific yyyy MM dd format, but all divided in several places, and then I had to search several sources to get what I need or make custom adjustments to suit my needs, so here is my bundled code list about possible and most common conversions of dates and times that I have come across.

Solution:

<?php

//curent DateTime
echo 'current DateTime';
echo '<br/>';
$currentDate=new DateTime(); //this returns the current date time
echo 'ISO 8601 (yyyy-mm-dd HH:mm:ss)='.$currentDate->format('Y-m-d H:i:s');
echo '<br/>';
echo 'yyyymmdd='.$currentDate->format('Ymd');
echo '<br/>';
echo 'mm/dd/yyyy='.$currentDate->format('m/d/Y');
echo '<br/>';
echo 'dd.mm.yyyy='.$currentDate->format('d.m.Y');
echo '<br/> Just the time - ';
echo 'HH:mm='.$currentDate->format('H:i');
echo '<br/><br/>';

//Custom string to DateTime
echo 'Custom string to DateTime';
echo '<br/>';
$customDateTime = DateTime::createFromFormat('Y-m-d H:i:s', '2016-11-21 21:53:05');
echo 'ISO 8601 (yyyy-mm-dd HH:mm:ss)='.$customDateTime->format('Y-m-d H:i:s');
echo '<br/>';
$customDateTime = DateTime::createFromFormat('m/d/Y', '11/21/2016'); //puts the current time !
echo 'ISO 8601 (yyyy-mm-dd HH:mm:ss)='.$customDateTime->format('Y-m-d H:i:s');
echo '<br/>';
$customDateTime = DateTime::createFromFormat('d.m.Y', '21.11.2016'); //puts the current time !
echo 'ISO 8601 (yyyy-mm-dd HH:mm:ss)='.$customDateTime->format('Y-m-d H:i:s');
echo '<br/><br/>';

//one liners 
echo 'One liners ';
echo '<br/>';
$customDateString='2016-11-21';
echo 'yyyy-mm-dd to dd-mm-yyyy = '.date_format(date_create_from_format('Y-m-d', $customDateString), 'd-m-Y');


?>

Output:


current DateTime
ISO 8601 (yyyy-mm-dd HH:mm:ss)=2016-12-12 15:24:23
yyyymmdd=20161212
mm/dd/yyyy=12/12/2016
dd.mm.yyyy=12.12.2016
Just the time - HH:mm=15:24

Custom string to DateTime
ISO 8601 (yyyy-mm-dd HH:mm:ss)=2016-11-21 21:53:05
ISO 8601 (yyyy-mm-dd HH:mm:ss)=2016-11-21 15:24:23
ISO 8601 (yyyy-mm-dd HH:mm:ss)=2016-11-21 15:24:23

One liners
yyyy-mm-dd to dd-mm-yyyy = 21-11-2016

This example was done with PHP Version 5.6.15  running on Apache/2.4.17 (Win32)

Leave a Reply

Your email address will not be published. Required fields are marked *