HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Date and Time

Handling dates and times is a core part of web development, whether for displaying post dates, scheduling tasks, or recording transaction times. PHP's date() function is the primary tool for formatting local dates and times.


1. The date() Function

The date() function formats a local date and time, and returns the formatted date string.

Syntax: date(format, timestamp)

Basic Date Formatting

  • d - Represents the day of the month (01 to 31)
  • m - Represents a month (01 to 12)
  • Y - Represents a year (in four digits)
  • l (lowercase 'L') - Represents the day of the week
<?php
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l"); // e.g: Monday
?>

2. Time Formatting

You can also format time using the following characters:

  • h - 12-hour format of an hour (01 to 12)
  • i - Minutes with leading zeros (00 to 59)
  • s - Seconds with leading zeros (00 to 59)
  • a - Lowercase Ante meridiem and Post meridiem (am or pm)
<?php
    echo "The time is " . date("h:i:sa");
?>

3. Setting the Timezone

By default, the time returned by date() depends on the server's configuration. To get the time for a specific location, you must set the timezone.

<?php
    date_default_timezone_set("Asia/Dhaka");
    echo "The time in Dhaka is " . date("h:i:sa");
?>
Important: Always set the timezone at the beginning of your script if your application relies on accurate local time.
Automatic Copyright Year: Use © 2020-<?php echo date("Y");?> to keep your footer copyright years always up to date automatically!

Formatting Reference

Char Description Example
YYear (4 digits)2024
MShort Month nameJan
dDay (01-31)17
H24-hour format14
iMinutes05