Menu
Coddy logo textTech

Intro to the DateTime Object

Part of the Logic & Flow section of Coddy's PHP journey — lesson 48 of 68.

While the procedural functions like date(), time(), and strtotime() work well for basic date operations, PHP offers a more powerful and flexible approach through the DateTime class. This object-oriented method provides better organization, clearer syntax, and more advanced functionality for working with dates and times.

The DateTime class represents a specific moment in time as an object, which you can then manipulate and format using various methods. Unlike procedural functions that work with separate timestamps and format strings, a DateTime object encapsulates both the date/time data and the operations you can perform on it.

<?php
$now = new DateTime();
echo $now->format('Y-m-d H:i:s');  // Outputs something like: 2024-03-15 14:30:25
?>

Creating a new DateTime object without any parameters automatically sets it to the current date and time.

The object-oriented approach makes your code more readable and maintainable, especially when you need to perform multiple operations on the same date. You'll find this particularly useful as you work with more complex date calculations and formatting requirements.

challenge icon

Challenge

Easy

You will receive one input: a date string in the format Y-m-d H:i:s (example: 2024-03-15 14:30:25).

Read the input date string, create a DateTime object using this date string as a parameter, and print the DateTime object directly.

When you create a DateTime object with a date string parameter, it represents that specific moment in time instead of the current date and time. Simply echo the object to display it.

Input format: One line containing a date string in the format Y-m-d H:i:s (example: 2024-03-15 14:30:25)

Expected output: The date and time formatted as Y-m-d H:i:s

Try it yourself

<?php
// Read the date string input
$dateString = trim(fgets(STDIN));

// TODO: Create a DateTime object using the date string and print it


?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow