News:

Alert!!! HTML Evaluation 01- Quiz

Main Menu

PHP Date and Time: 010

Started by Cohort Master, Apr 01, 2024, 07:37 AM

Previous topic - Next topic

Cohort Master

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.

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:
<?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");
?>


Formatting the Dates and Times with PHP
The format parameter of the date() function is in fact a string that can contain multiple characters allowing you to generate a date string containing various components of the date and time, like day of the week, AM or PM, etc. Here are some the date-related formatting characters that are commonly used in format string:

d - Represent day of the month; two digits with leading zeros (01 or 31)
D - Represent day of the week in text as an abbreviation (Mon to Sun)
m - Represent month in numbers with leading zeros (01 or 12)
M - Represent month in text, abbreviated (Jan to Dec)
y - Represent year in two digits (08 or 14)
Y - Represent year in four digits (2008 or 2014)
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting.

Similarly you can use the following characters to format the time string:

h - Represent hour in 12-hour format with leading zeros (01 to 12)
H - Represent hour in in 24-hour format with leading zeros (00 to 23)
i - Represent minutes with leading zeros (00 to 59)
s - Represent seconds with leading zeros (00 to 59)
a - Represent lowercase ante meridiem and post meridiem (am or pm)
A - Represent uppercase Ante meridiem and Post meridiem (AM or PM)
PHP Tip - Automatic Copyright Year
Use the date() function to automatically update the copyright year on your website:

Example
Copyright 2010-<?php echo date("Y");?>