← Back to Chapters

PHP date_create() & date_format()

? PHP date_create() & date_format()

? Quick Overview

The date_create() function creates a DateTime object, while date_format() converts that object into a readable date string. Together, they form the foundation of date and time handling in PHP.

? Key Concepts

  • DateTime objects store date and time data
  • Formatting controls how dates are displayed
  • Supports custom formats and time zones

⚙️ Syntax / Theory

? View Code Example
// Create a DateTime object
date_create(time, timezone);

// Format a DateTime object
date_format(date, format);

? Example 1: Using date_create()

This example creates a DateTime object for a specific date.

? View Code Example
// Create a date for Christmas 2025
<?php
$date = date_create("2025-12-25");
echo date_format($date, "Y-m-d");
?>

? Output

2025-12-25

? Example 2: Custom Date Formatting

? View Code Example
// Format date with day name and time
<?php
$date = date_create("2025-12-25 10:30:00");
echo date_format($date, "l, F j, Y h:i A");
?>

? Output

Friday, December 25, 2025 10:30 AM

? Example 3: Current DateTime

? View Code Example
// Get current date and time
<?php
$current = date_create();
echo date_format($current, "D, d M Y H:i:s");
?>

? Visual Flow (Date Handling)

date_create() DateTime Object date_format()

? Use Cases

  • Displaying formatted dates in dashboards
  • Logging timestamps
  • User-friendly date output
  • Time-based calculations

✅ Tips & Best Practices

  • Always work with DateTime objects instead of raw strings
  • Use readable formats for users and ISO formats for storage
  • Be aware of the server timezone

? Try It Yourself

  • Create a DateTime object for your birthday
  • Display only month and year
  • Show current time in different formats
  • Calculate difference between two dates