PHP Convert DateTime To String Example


Share:
 | Published By: Admin | Published On: Dec 10, 2021 | Category: 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.

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

It will help you...

Share: