Dominar PHP Date(): formatear la fecha y la hora como un profesional

17 de noviembre de 2025

PHP’s date() function is one of the most powerful and commonly used tools for handling date and time formatting in web applications. Whether you’re building a blog, e-commerce platform, or dashboard, displaying dates in a user-friendly way is essential. In this comprehensive guide,
we’ll dive deep into the
date() function, explore its syntax, format specifiers, real-world examples, best practices, and common pitfalls.

What is PHP Date() Function?

El date() function in PHP formats a local date and time according to a specified format string. It returns a string representing the formatted date/time.

Sintaxis básica

PHP

string date(string $format, ?int $timestamp = null)

  • $format: A string containing format specifiers (e.g., Y, metro, d).
  • $timestamp: Optional Unix timestamp. If omitted, the current time is used.

Note: As of PHP 8.0+, the second parameter is nullable (?int).

Key PHP Date Format Specifiers

Here’s a quick reference table of the most commonly used format characters:

SpecifierDescripciónExample Output
Y4-digit year2026
y2-digit year25
metroMonth (01–12)11
nMonth without leading zeros (1–12)11
FFull month nameNovember
MShort month name (3 letters)Nov
dDay of month with leading zeros17
jDay without leading zeros17
lFull weekday nameMonday
DShort weekday (3 letters)Mon
H24-hour format (00–23)11
h12-hour format (01–12)11
iMinutes with leading zeros37
sSeconds with leading zeros45
AUppercase AM/PMAM
aLowercase am/pmam
TTimezone abbreviationIST
cISO 8601 format2026-11-17T11:37:45+05:30
rRFC 2822 format
Mon, 17 Nov 2026 11:37:45
+0530

Basic Examples of PHP Date Format

1. Current Date and Time

PHP

echo date(‘Y-m-d H:i:s’); 

// Output: 2026-11-17 11:37:45
2. Human-Readable Format

PHP

echo date(‘l, F j, Y \a\t g:i A’); 

// Output: Monday, November 17, 2026 at 11:37 AM

Utilice \ to escape characters like en so they appear literally.

3. Short Date

PHP

echo date('d/m/Y'); 

// Output: 17/11/2026
4. Time Only

PHP

echo date('h:i A'); 

// Output: 11:37 AM

Working with Timestamps

You can format any Unix timestamp:

PHP

$timestamp = strtotime('2026-01-01 00:00:00');

echo date('Y-m-d', $timestamp);

// Output: 2026-01-01
Combine with strtotime()

PHP

echo date('F j, Y', strtotime('+7 days'));

// Output: November 24, 2026

Timezone Handling (Critical!)

De manera predeterminada, date() uses the server’s default timezone. Always set it explicitly:

PHP

date_default_timezone_set('Asia/Kolkata'); // IST

echo date('Y-m-d H:i:s T');

// Output: 2026-11-17 11:37:45 IST

Best Practice: Set timezone at the top of your config file or entry point.

Real-World Use Cases for PHP Date Format

1.Blog Post Dates

PHP

$post_date = '2026-11-10 14:30:00';

echo date('M j, Y', strtotime($post_date));

// Output: Nov 10, 2026
2. Relative Time (“2 hours ago”)

PHP

function timeAgo($timestamp) {

    $diff = time() - $timestamp;

    if ($diff < 60) return "$diff seconds ago";

    if ($diff < 3600) return round($diff/60) . " minutes ago";

    if ($diff < 86400) return round($diff/3600) . " hours ago";

    return date('M j', $timestamp);

}

echo timeAgo(strtotime('2026-11-17 09:00:00'));

// Output: 2 hours ago
3. Event Countdown

PHP

$event = strtotime('2026-12-25 00:00:00');

$now = time();

$days_left = floor(($event - $now) / 86400);

echo "Christmas is in $days_left days!";

// Output: Christmas is in 38 days!

Common Pitfalls & How to Avoid Them

IssueSolución
Wrong timezoneAlways use date_default_timezone_set()
Y2K-like bugs with yPrefiero Y for full year
Leading zeros confusionUtilice j en lugar de d if you don’t want zeros
Locale issuesUtilice setlocale() + strftime() for localized names
Deprecated in future?No! But consider DateTime for complex operations

Pro Tips

1. Use DateTime for Advanced Needs

2. php

$dt = new DateTime('now', new DateTimeZone('Asia/Kolkata'));

3. echo $dt->format('Y-m-d H:i:s');

4. Cache Formatted Dates
Avoid calling date() in loops for performance.

5. Validate Input Timestamps

6. PHP

if ($timestamp === false) {

    $timestamp = time();

7. }

8. Internationalization

9. PHP

setlocale(LC_TIME, 'hi_IN');

10. echo strftime('%e %B %Y'); // Hindi date

Bonus: One-Liner Date Formats

PHP
// ISO
date('c');

// US Format
date('m/d/Y h:i A');

// EU Format
date('d.m.Y H:i');

Conclusión

Mastering date() is about understanding its format specifiers, timezone handling, y integration with strtotime(). Mientras que DateTime offers more power for complex scenarios, date() remains lightweight, fast, and perfect for 90% of use cases. Carmatec, un liderazgo empresa de desarrollo PHP, leverages to deliver clean, efficient, and reliable time-based functionality.