Skip to content

All topics  /  PHP

How To Convert DateTime To String Using PHP ?

PHP ·

Teams applying “How To Convert DateTime To String Using PHP ?” in a production project can use the full explanation to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.

Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.

How To Convert DateTime To String Using PHP ?

Hello Friends,

Now let's see example of how to convert datetime to string example. We will check how to convert datetime to string. This is a short guide on convert datetime to string in php. Here you will learn how to convert datetime to string. Let's get started with how to convert datetime to string in php.

Here i will give you many example how to convert datetime to string using php.

Let's start this following step.

Example : 1

By using Format method

In the Format method, we can convert the DateTime object to a string.

The DateTime to string program is programmed below:

<?php
    $date = date_create('2021-11-23  05:06:07');
    //This convert formate of date
    echo 'Output :'.' '.date_format($date, 'd-m-Y');    
?>

Output:

23-11-2021

Example : 2

By using list() method:

The list() method is used to convert the DateTime object to string.

The shorter way of list method is programmed below:

Using list method to display the datetime

<?php
    list($day, $month, $year, $hour, $min, $sec) = explode("/", date('d/m/Y/h/i/s')); 
    //Display the datetime
    echo "Output :"." ".$month . '/' . $day . '/' . $year . ' ' . $hour . ':' . $min . ':' . $sec;
?>

Output:

12/09/2021 05:27:30

Example : 3

By using strtotime method

<?php
    $input = '06/10/2011 19:00:02';
    $date = strtotime($input);
    echo "Output :"." ".date('d/M/Y h:i:s', $date);
?>

Output:

10/Jun/2011 07:00:02

Example : 4

By using custom function

<?php
    function date_time_to_string($input)
    {
    	$date = strtotime($input);
    	echo "Output :"." ".date('d/M/Y h:i:s', $date);
    }
    $input = '06/10/2011 19:00:02';
    date_time_to_string($input);
?>

Output:

10/Jun/2011 07:00:02

Example : 5

Change current date formate using str_replace method

<?php
     $currentDate = date("Y/m/d");
     $date = str_replace('/', '-', $currentDate);
     echo "Output :"." ".$date;
?>

Output:

2021-12-09

# PHP