1. Home
  2. Coding
  3. How to convert DateTime to String in PHP

How to convert DateTime to String in PHP

Share

In this article, we will learn how to convert a Date or a DateTime into a String in PHP.

The Format method from DateTime

To convert a Date or a DateTime object into a String in PHP, we can use the format method from the DateTime class. As the name already says, the format method can help us formatting a DateTime object into multiple different formats.

To do so, we simply need to specify the desired format as an argument when calling the format method. That’s it!

In the following section, we will see a practical example of how to use the format method to return a string according to the given format. This method is supported from PHP 5 >= 5.2.1 to the latest version.

DateTime to String example

Let’s now take a look at a practical example. In the code below, we will use format to simply convert a DateTime object into different String formats:

<?php

$current_datetime = new DateTime( '2021-04-17 17:29:15' );

$date_time = $current_datetime->format( 'd/m/Y, H:i:s' );
echo 'datetime: ' . $date_time . '<br />';

$date = $current_datetime->format( 'd/m/Y' );
echo 'date: ' . $date . '<br />';

$time = $current_datetime->format( 'H:i:s' );
echo 'time: ' . $time . '<br />';

$day = $current_datetime->format( 'd' );
echo 'day: ' . $day . '<br />';

$month = $current_datetime->format( 'm' );
echo 'month: ' . $month . '<br />';

$year = $current_datetime->format( 'Y' );
echo 'year: ' . $year . '<br />';

In the example below, we used the DateTime class to initialize the $current_datetime variable with a new DateTime object and using a string. Subsequently, we used the format method to convert the DateTime object into the following formats:

  • DateTime: using the 'd/m/Y, H:i:s' pattern
  • Date: using the 'd/m/Y' pattern
  • Time: using the 'H:i:s' pattern
  • Day: using the 'd' pattern
  • Month: using the 'm' pattern
  • Year: using the 'Y' pattern.

If we run the code below, the output is:

datetime: 17/04/2021, 17:29:15
date: 17/04/2021
time: 17:29:15
day: 17
month: 04
year: 2021

External resources:

If you like our post, please share it: