PHP Date and Time
PHP provides a powerful set of functions for manipulating dates and times.
1. The date() Function
The date() function formats a timestamp to a more readable date and time.
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("l"); // Outputs day of week
Common Format Characters
d- Day of the month (01 to 31)m- Month (01 to 12)Y- Year (in 4 digits)l- Day of the weekH- 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)
2. Get a Time (Timestamp)
The time() function returns the current time as a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
$t = time();
echo($t . "<br>");
echo(date("Y-m-d", $t));
3. Create a Date with mktime()
The mktime() function returns the Unix timestamp for a date.
Syntax: mktime(hour, minute, second, month, day, year)
$d = mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
4. String to Time strtotime()
The strtotime() function is used to convert a human readable string to a Unix time.
$d = strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
$d = strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d);
5. Timezones
If the time returned is not correct, it's probably because your server is in another country or set up for a different timezone.
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");