Friday, October 24, 2025
HomeLanguagesHow to convert DateTime to String using PHP ?

How to convert DateTime to String using PHP ?

The task is to convert DateTime to String using PHP. There are two ways to convert it.  

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:

Example:

PHP




<?php
  
// Store datetime in variable today
$today = date("d/m/Y H:i:s");    
  
if ($today) { 
    echo $today
  
// If unknown time 
} else {  
    echo "can't display time"
}
?>


Output:

07/05/2021 17:57:38

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:

PHP




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


Output:

05/07/2021 05:58:48
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS