What is the Date() method in PHP?
PHP's Date() function manages date, time, or both. This function modifies the timestamp to a more understandable date and time.
Syntax
date(format,timestamp)
Parameters
format: This parameter defines the structure of the timestamp.
timestamp: This defines a timestamp. By default, it is the current date and time. This is an optional parameter.
Get date
Some commonly used patterns for the format parameter are the following:
d: Day (01-31)m: Month (1-12)y: Year (4 digits)l: Day of the week
<?phpecho "Day rightnow is " . date("l") ."\n";echo "Today's Date: " . date("Y.m.d") ."\n";echo "Today's Date: " . date("Y/m/d") ."\n";echo "Today's Date: " . date("Y-m-d") ;?>
Explanation
- Line 2: We print the current day by passing
lin thedate()function. - Line 3-5: We print the current data in the
Year-Month-Dayformat with different separators. These separators are.,/, and-.
Get time
Some commonly used patterns for the format parameter are the following:
Hfor 24-hour time formathfor 12-hour time formatifor minutessfor secondsafor lowercase ante meridiem and post meridiem (am or pm)
<?phpecho "Current time in 24hr format is " . date("H:i:sa")."\n";echo "Current time in 12hr format is " . date("h:i:sa");?>
Explanation
- Line 2: We print the current time in 24-hour format through the
date()function.Hspecifies the 24-hour format. - Line 4: We print the current time in the 12-hour format through the
date()function.hspecifies the 12-hour format.
How to set the time zone
<?phpdate_default_timezone_set("America/Chicago");echo "The current time in Chicago is " . date("h:i:sa");?>
Explanation
- Line 2: The
date_default_timezone_set()function sets the time zone according to the country and the state/city defined in the parameters. - Line 3: The
date()function prints the current time according to the time zone set above.
Create a date
The mktime() function returns the Unix timestamp, i.e., the difference in seconds between the time defined and the Unix Epoch (January 1 1970 00:00:00 GMT).
mktime(hour, minute, second, month, day, year)
Example
<?php$new_date=mktime(10, 49, 35, 4, 14, 2022);echo "Created date is " . date("Y/m/d h:i:sa", $new_date);?>
Explanation
- Line 2: The
mktime()function sets the custom time. - Line 3: We print the date by defining a specific format through the
date()function and by passing thenew_dateobject to it.