- PHP Date and Time
- The PHP Date() Function
- Syntax
- Get a Date
- Example
- PHP Tip — Automatic Copyright Year
- Example
- Get a Time
- Example
- Get Your Time Zone
- Example
- Create a Date With mktime()
- Syntax
- Example
- Create a Date From a String With strtotime()
- Syntax
- Example
- Example
- More Date Examples
- Example
- Example
- Complete PHP Date Reference
- date_format
- Return Values
- Converting a PHP timestamp to a date(time)
- In this article
- Getting a Timestamp
- Timestamp To Date Time Object
- Formatting a Date
- Formatting a Time
- Date with TimeZone
- Converting a Timestamp to Date Time
- Key Takeaways
PHP Date and Time
The PHP date() function is used to format a date and/or a time.
The PHP Date() Function
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 |
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.
Get a Date
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:
- 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
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:
Example
echo «Today is » . date(«Y/m/d») . «
«;
echo «Today is » . date(«Y.m.d») . «
«;
echo «Today is » . date(«Y-m-d») . «
«;
echo «Today is » . date(«l»);
?>?php
PHP Tip — Automatic Copyright Year
Use the date() function to automatically update the copyright year on your website:
Example
Get a Time
Here are some characters that are commonly used for times:
- H — 24-hour format of an hour (00 to 23)
- h — 12-hour format of an hour with leading zeros (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)
The example below outputs the current time in the specified format:
Example
Note that the PHP date() function will return the current date/time of the server!
Get Your Time Zone
If the time you got back from the code is not correct, 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 the timezone you want to use.
The example below sets the timezone to «America/New_York», then outputs the current time in the specified format:
Example
Create a Date With mktime()
The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above).
The PHP 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 with the date() function from a number of parameters in the mktime() function:
Example
Create a Date From a String With strtotime()
The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Syntax
The example below creates a date and time from the strtotime() function:
Example
PHP is quite clever about converting a string to a date, so you can put in various values:
Example
$d=strtotime(«next Saturday»);
echo date(«Y-m-d h:i:sa», $d) . «
«;
However, strtotime() is not perfect, so remember to check the strings you put in there.
More Date Examples
The example below outputs the dates for the next six Saturdays:
Example
$startdate = strtotime(«Saturday»);
$enddate = strtotime(«+6 weeks», $startdate);
?php
while ($startdate < $enddate) echo date("M d", $startdate) . "
«;
$startdate = strtotime(«+1 week», $startdate);
>
?>
The example below outputs the number of days until 4th of July:
Example
$d1=strtotime(«July 04»);
$d2=ceil(($d1-time())/60/60/24);
echo «There are » . $d2 .» days until 4th of July.»;
?>?php
Complete PHP Date Reference
For a complete reference of all date functions, go to our complete PHP Date Reference.
The reference contains a brief description, and examples of use, for each function!
date_format
The format of the outputted date string . See the formatting options below. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string ‘D, d M Y H:i:s’ .
format character | Description | Example returned values |
---|---|---|
Day | — | — |
d | Day of the month, 2 digits with leading zeros | 01 to 31 |
D | A textual representation of a day, three letters | Mon through Sun |
j | Day of the month without leading zeros | 1 to 31 |
l (lowercase ‘L’) | A full textual representation of the day of the week | Sunday through Saturday |
N | ISO 8601 numeric representation of the day of the week | 1 (for Monday) through 7 (for Sunday) |
S | English ordinal suffix for the day of the month, 2 characters | st , nd , rd or th . Works well with j |
w | Numeric representation of the day of the week | 0 (for Sunday) through 6 (for Saturday) |
z | The day of the year (starting from 0) | 0 through 365 |
Week | — | — |
W | ISO 8601 week number of year, weeks starting on Monday | Example: 42 (the 42nd week in the year) |
Month | — | — |
F | A full textual representation of a month, such as January or March | January through December |
m | Numeric representation of a month, with leading zeros | 01 through 12 |
M | A short textual representation of a month, three letters | Jan through Dec |
n | Numeric representation of a month, without leading zeros | 1 through 12 |
t | Number of days in the given month | 28 through 31 |
Year | — | — |
L | Whether it’s a leap year | 1 if it is a leap year, 0 otherwise. |
o | ISO 8601 week-numbering year. This has the same value as Y , except that if the ISO week number ( W ) belongs to the previous or next year, that year is used instead. | Examples: 1999 or 2003 |
X | An expanded full numeric representation of a year, at least 4 digits, with — for years BCE, and + for years CE. | Examples: -0055 , +0787 , +1999 , +10191 |
x | An expanded full numeric representation if requried, or a standard full numeral representation if possible (like Y ). At least four digits. Years BCE are prefixed with a — . Years beyond (and including) 10000 are prefixed by a + . | Examples: -0055 , 0787 , 1999 , +10191 |
Y | A full numeric representation of a year, at least 4 digits, with — for years BCE. | Examples: -0055 , 0787 , 1999 , 2003 , 10191 |
y | A two digit representation of a year | Examples: 99 or 03 |
Time | — | — |
a | Lowercase Ante meridiem and Post meridiem | am or pm |
A | Uppercase Ante meridiem and Post meridiem | AM or PM |
B | Swatch Internet time | 000 through 999 |
g | 12-hour format of an hour without leading zeros | 1 through 12 |
G | 24-hour format of an hour without leading zeros | 0 through 23 |
h | 12-hour format of an hour with leading zeros | 01 through 12 |
H | 24-hour format of an hour with leading zeros | 00 through 23 |
i | Minutes with leading zeros | 00 to 59 |
s | Seconds with leading zeros | 00 through 59 |
u | Microseconds. Note that date() will always generate 000000 since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. | Example: 654321 |
v | Milliseconds. Same note applies as for u . | Example: 654 |
Timezone | — | — |
e | Timezone identifier | Examples: UTC , GMT , Atlantic/Azores |
I (capital i) | Whether or not the date is in daylight saving time | 1 if Daylight Saving Time, 0 otherwise. |
O | Difference to Greenwich time (GMT) without colon between hours and minutes | Example: +0200 |
P | Difference to Greenwich time (GMT) with colon between hours and minutes | Example: +02:00 |
p | The same as P , but returns Z instead of +00:00 (available as of PHP 8.0.0) | Examples: Z or +02:00 |
T | Timezone abbreviation, if known; otherwise the GMT offset. | Examples: EST , MDT , +05 |
Z | Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. | -43200 through 50400 |
Full Date/Time | — | — |
c | ISO 8601 date | 2004-02-12T15:19:21+00:00 |
r | » RFC 2822/» RFC 5322 formatted date | Example: Thu, 21 Dec 2000 16:01:07 +0200 |
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | See also time() |
Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate() .
Note:
Since this function only accepts int timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create() .
Return Values
Returns the formatted date string on success.
Converting a PHP timestamp to a date(time)
In this PHP tutorial, we’re going to convert a timestamp in PHP to a date (optionally with time) using custom formatting. We’ll start by getting the current time stamp and display it using the simple date function. Next, we’ll use the current timestamp to create a Date Time object, format the date and display it. We’ll then view some of the date and time formatting options, followed by the Date Time Zone class. And finally, we’ll create a function to convert a timestamp to DateTime with time zone and date format parameters.
In this article
Getting a Timestamp
Let’s start with a basic PHP function to get the timestamp, we’ll use time() to get the current timestamp and date to format the output.
The time stamp saved in $now is similar to 1610246191, so we format it using date(‘Y-m-d’, $now) for a user friendly output. The timestamp returned is in seconds, see the microtime function to get a timestamp including micro seconds.
Timestamp To Date Time Object
While we can use the date function to format our date or timestamp, it isn’t the object oriented way of doing it. Let’s create a DateTime object and set the timestamp.
We can then output the date and time using the format method with the ‘c’ datetime parameter.
Formatting a Date
The format method can format a date in many different ways, common formats are: Y-m-d and d/m/Y .
The PHP manual has many more date formats available.
Formatting a Time
The DateTime class can also format the same timestamp in time only format.
We use the H:i:s(Hour, Minute, Second) format in the code above.
Date with TimeZone
The DateTime object can be set to use a specific time zone. We create a new DateTimeZone with a particular time zone and call the setTimeZone method on our DateTime object.
The DateTimeZone class has many timezone options. The PHP code example above displays the same timestamp using different time zones.
Converting a Timestamp to Date Time
Our final function is a combination of DateTime and DateTimeZone with 3 parameters: a timestamp, time zone and date/time format with default formatting.
Our custom PHP function timeStampToDateTime takes a timestamp as first parameter, which could be the current timestamp or any other time stamp (maybe a timestamp from a db). It uses the timezone and format to return a human readable date time string.
Key Takeaways
- We can use the time() function to get the current timestamp and the date function to format a timestamp.
- The DateTime class is the object oriented way of working with dates and times.
- The DateTimeZone class provides time zone functionality which can be used with the DateTime class to work with dates and times.
- The format , setTimeZone and setTimeStamp methods are the primary methods we can use to convert a timestamp to date/time.
- Related PHP functions: microtime
This is the footer. If you’re reading this, it means you’ve reached the bottom of the page.
It would also imply that you’re interested in PHP, in which case, you’re in the right place.
We’d love to know what you think, so please do check back in a few days and hopefully the feedback form will be ready.