The PHP date() function formats a timestamp to a more readable date and time.
Syntax
Parameter | Description |
---|---|
format | Required. Specifies the format of the timestamp |
timestamp | Optional. Specifies a timestamp. Default is the current date and time |
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional formatting.
The example below formats today's date in three different ways:
See this example:
Use the date() function to automatically update the copyright year on your website:
See this example:
Here are some characters that are commonly used for times:
The example below outputs the current time in the specified format:
See this example:
If the time you got back from the code is not the right time, it's probably because your server is in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set a timezone to use.
The example below sets the timezone to "America/New_York", then outputs the current time in the specified format:
See this example:
The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used (as shown in the examples above).
The mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
Syntax
The example below creates a date and time from a number of parameters in the mktime() function:
See this example:
The PHP strtotime() function is used to convert a human readable string to a Unix time.
Syntax
The example below creates a date and time from the strtotime() function:
See this example:
PHP is quite clever about converting a string to a date, so you can put in various values:
See this example:
However, strtotime() is not perfect, so remember to check the strings you put in there.
The example below outputs the dates for the next six Saturdays:
See this example:
The example below outputs the number of days until 4th of July:
See this example: