Date and Time Functions in PHP
The date() function used to converts a timestamp to readable date and time format.
Syntax
<?php date(format,timestamp); ?>
- format : which format we want our output.
- timestamp : (optional).if not given, It will take the current date time on the server.
What is a Timestamp?
Number of Seconds between Current time and 1st January 1970 00:00:00. It is depends on the default time zone.
The following code shows, how to display the current timestamp.
Timestamp
<?php echo time(); ?>
Get current Date and Change Formats :
<?php #Get Current Date $current_date=date("d-m-Y"); echo $current_date; #Change date format $simple_date="2020-12-31"; echo date("Y",strtotime($simple_date)); # 2020 echo date("d-m-Y",strtotime($simple_date)); # 31-12-2020 echo date("Y M d",strtotime($simple_date)); # 2020 Dec 31 echo date("D Y M",strtotime($simple_date)); # Thu 2020 Dec #Convert 'yyyy-mm-dd' to 'dd-mm-yyyy' $date1="2020-12-31"; $format_date=date("d-m-Y",strtotime($date1)); echo $format_date; # 31-12-2020 #Convert 'dd-mm-yyyy' to 'yyyy-mm-dd' $date2="31-12-2020"; $format_date=date("Y-m-d",strtotime($date2)); echo $format_date; # 2020-12-31 ?>
- d - Day of the Month (01 to 31)
- D - Day Abbrivation (Mon tp Sun)
- m - Month (01 to 12)
- M - First 3 letters of Month Name (Jan to Dec)
- F - Month name (January to December)
- y - Year (94)
- Y - Year (1994)
Get current Time :
<?php #set the timezone Programmatically date_default_timezone_set('Asia/Kolkata'); #Get Current Time: $current_time=date("h:i:s a"); echo $current_time; ?>
- H - 24 Hour Format ( 01 to 24)
- h - 12 Hour Format ( 01 to 12)
- i - Minutes ( 00 to 59)
- s - Seconds ( 00 to 59)
- a - am or pm
- A - AM or PM