PHP Date and Time
The PHP date() function is used to format a date and/or a time.
Syntax:
1 |
date(format,timestamp); |
Parameter | Description |
---|---|
format | Required. Specifies the format of the timestamp |
timestamp | Optional. Specifies a timestamp. Default is the current date and time |
Ex:
1 2 3 4 5 6 |
<?php echo "Today's date is :"; $today = date("d-m-Y"); echo $today; ?> |
Output: Today’s date is: 26-03-2020
Formatting options available in date() function:
The format parameter of the date() function is a string that can contain multiple characters allowing to generate dates in various formats.
Date-related formatting characters that are commonly used in the format string:
Character | What It Means |
d | Day of the Month (Numeric 01 or 31) |
D | Day of the Week (String Mon to Sun) |
l | Day of the Week (String Mon to Sun) |
F | Month (String Jan to Dec) |
M | Month (String Jan to Dec) |
m | Month (Numeric 01 to 12) |
Y | Year in four-digit (Numeric 2008 or 2020 ) |
y | Year in two-digit (Numeric 08 or 20 ) |
h | Hour (in 12-hour format) |
H | Hour (in 24-hour format) |
a | AM or PM |
i | Minute |
s | Second |
Example of Date Format
1 2 3 4 5 6 |
<?php echo date("d/m/Y") . "\n"; echo date("d-m-Y") . "\n"; echo date("d.m.Y") . "\n"; echo date("d.M.Y"); ?> |
Output:
1 2 3 4 |
26/12/2020 26-12-2020 26.12.2020 26.Dec.2020 |
Example of Time Format
1 2 3 4 |
<?php echo date("h:i:s") . "\n"; echo date("M,d,Y h:i:s A") . "\n"; echo date("h:i a"); |
Output:
1 2 3 |
08:48:12 Dec,26,2020 08:48:12 PM 08:48 pm |
PHP time() Function
The time() function is used to get the current time as a Unix timestamp. A UNIX timestamp for a particular time point represents the number of seconds that have elapsed between midnight on January 1970, and that time point. So, for example, the time point January 5 2008 10:15:00 AM in UNIX timestamp format would be 1199508300.
PHP can automatically turn a date value into a UNIX timestamp with mktime() function, which accepts day, month, year, hour, minute, and second arguments and returns a UNIX timestamp corresponding to that instant in time.
Below program explains usage of time() function in PHP:
1 2 3 4 5 6 7 |
<?php $timestamp = time(); echo($timestamp); echo "\n"; echo(date("F d, Y h:i:s A", $timestamp)); ?> |
Output:
1585236776
March 26, 2020 04:32:56 PM