PHP Date and Time
In PHP, date() function is a built-in function which is used to format date and/or a time. date() function format a timestamp into a more readable date and time format.
A timestamp is a sequence of characters, specifying the date and time at which a certain event occured.
Why do we need the date() function?
The computer system stores the dates and time in UNIX timestamp format, which is measured as a number of seconds since the beginning of the UNIX epoch (Janurary 1, 1970). Since there is a date() function in php which helps to converts a timestamp into more easy readable format.
In date() function, there are some important parameters which format the date and time.
- d : Represent the day of the month (01 to 31)
- m: Represent a month (01 to 12)
- Y: Represents a year (in four digits)
- l : Represents the day of the week
Along with formatting the date() function with these parameters, you can also insert other characters like hyphen (-), dot(.), or slash(/) in between the date to show additional formatting.
<?php echo "Today is ". date("Y-m-d")."<br>"; echo "Today is ". date("Y/m/d")."<br>"; echo "Today is ". date("Y.m.d")."<br>"; echo "Today is ". date("l")."<br>"; ?> #Output Today is 2021-07-21 Today is 2021/07/21 Today is 2021.07.21 Today is Wednesday
Similar to date() function, time() function with its additional parameters are also used to format time.
- H : 24-hour format of an hour (01 to 23)
- h : 12-hour format of an hour with leading zeroes (01 to 12)
- i : Minutes with leading zeroes (01 to 59)
- s : Seconds with leading zeroes (01 to 59)
- a : Lowercase Ante Meridiem and Post Meridiem (am or pm)
<?php echo "The time is ". date("h:i:sa"); ?> #Output The time is 08:12:55pm
NOTE: The php date() function returns the current date/time of the server.
Get your Time zone:
Sometimes you won’t get the correct date even if you’ve written the correct date() function in your code. This is due to the reason your server is loaded some other county where default time zone has been set up as per the country time zone. Now when you want to specify your country time zone in place of earlier one. You have to define your local time zone.
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 format.
<?php $dt = strtotime("10:30pm July 22 2021"); echo "Timestamp Date is ". date("Y-m-d h:i:sa", $dt); ?> #Output Timestamp Date is: 2021-07-22 10:30:00pm
Some more examples:
<?php $dt = strtotime("yesterday"); echo date("Y-m-d h:i:sa", $dt) . "<br>"; $dt = strtotime("tomorrow"); echo date("Y-m-d h:i:sa", $dt) . "<br>"; $dt = strtotime("next Sunday"); echo date("Y-m-d h:i:sa", $dt) . "<br>"; $dt = strtotime("+2 Months"); echo date("Y-m-d h:i:sa", $dt) . "<br>"; ?> #Output 2021-07-21 12:00:00am 2021-07-23 12:00:00am 2021-07-25 12:00:00am 2021-09-22 03:56:18am