Date and time in PHP
The date function
PHP has a very useful date function that can read in a Unix timestamp and output the date as a formatted string of your choice.
date(format [, optional Unix timestamp])
The timestamp is optional, if it is left out it will default to the current time.
Unix time stamps
An easy way to create Unix timestamps for use with the date function is to use mktime.
mktime([optional hour, minute, second, month, day, year])
All parameters in mktime are optional (from left to right i.e. if you want to specify a day then you have to specify a month), if they are left out they will default to the current date and time.
Date format string
Below are a list of common strings for the date function.
| Format character | Description |
|---|---|
| a | am - pm |
| A | AM - PM |
| d | Day of the month - (01 - 31) - leading zeros |
| D | Day of the week - 3 letters e.g. Mon |
| F | Month of the year - full - e.g. January |
| g | 12 hour format - (1 - 12 ) |
| G | 24 hour format - (0 - 23) |
| h | 12 hour format - (01 - 12 ) - leading zeros |
| H | 24 hour format - (00 - 23) - leading zeros |
| i | Minutes - (00 - 59) - leading zeros |
| J | Day of the month - (1 - 31) |
| l | Day of the week - Full - e.g. Monday |
| L | Leap year - (1=leap year) |
| m | Month of the year - numerical - (01 - 12) - leading zeros |
| M | Month of the year - 3 letters - e.g. Jan |
| n | Month of the year - numerical - (1 - 12) |
| O | Difference to Greenwich mean time e.g. +0200 |
| s | Seconds with leading zeros - (00-59) |
| S | Suffix of day of the month - e.g. st, nd, rd, th |
| t | Number of days in the month |
| T | Time zone |
| w | Numerical day of the week - (0 = Sunday, 1 = Monday) |
| W | Week of the year |
| Y | Year - full - 2005 |
| y | Year - 2 numbers - 05 |
| z | Day of year |
For the full list see the PHP website.
Examples
Below are a list of example uses of the date function.
date('J MS Y');
//outputs 1st Jan 2010
date('J MS Y', mktime(0, 0, 0, 1, 1, 2000));
//outputs 1st Jan 2000
Adobe Fireworks® Adobe Flash® and Adobe Photoshop® are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries.
MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Copyright Pixelcode 2005 - 2010