PHP Date and Time
The PHP date() function is used to format a date and/or a time. It can turn a timestamp into a more readable format for humans.
1. The date() Function
The syntax for the date function is: date(format, timestamp). The format parameter is required, while timestamp is optional (defaults to the current time).
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l"); // Displays the day of the week
?>
Common Date Characters:
- 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
2. Get a Simple Time
To get the time, you use specific characters in the date function:
- H - 24-hour format of an hour (00 to 23)
- 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. Get Your Time Zone
If the time returned is not correct, it is likely because your server is in another country. You can set the timezone specifically to your location.
<?php
date_default_timezone_set("Asia/Kolkata");
echo "The time in India is " . date("h:i:sa");
?>
4. Create a Date From a String
The strtotime() function is used to convert a human-readable string into a Unix timestamp.
<?php
$d = strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d = strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d = strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d);
?>
Tip: Always use date_default_timezone_set() at the top of your script if you are building an application that depends on local time (like a booking system or a log).