Display the date with PHP

Posted by Shek on April 12, 2008 under PHP | Be the First to Comment | Total View: 3,683 views

Editor’s note: I recently worked on a web project which I need to add the date on a page. I used the PHP function date( ) to accomplish the job. Here are my examples for your reference.

In order to show the time, we have to print it out onto the screen, and we use “echo” or “print” to do so:
If we just echo out the with the date() function:

We will get an error message because the date( ) function needs at least 1 parameter.

There are many parameters for date( ) function and here are a few useful one which I want to talk about:
Year:
“Y” – a big Y shows 4 digits of the current year (the server’s time)
<?php echo date(Y); ?> we get 2008, if you test the code in year 2008.

“y” – a small y shows 2 last digits of the current year (the server’s time)
<?php echo date(y); ?>we get 08, if you test the code in year 2008.

Month:
“F” – a big F shows the English name of the current month (the server’s time)
<?php echo date(F); ?> we get April, if you test the code in April.

“M” – a big M shows the short from in 3 letters of the English name of the current month (the server’s time)
<?php echo date(M); ?> we get Apr, if you test the code in April.

“m” – a small m shows the current month in 2 digits (the server’s time)
<?php echo date(M); ?> we get 04, if you test the code in April.

Day:
“d” – a small d shows the day of the month in 2 digits (the server’s time)
<?php echo date(d); ?> we get 12, if you test the code on the 12th of the month.

“j” – a small j shows the day of the month in 2 digits but for 1 digit for 1st to 9th of the month (the server’s time)
<?php echo date(d); ?> we get 9, if you test the code on the 9th of the month.

Now here are a few example to have a complete date:

To have a date such as “day/month/year” – <?php echo date(”d/m/Y”); ?> we get “12/04/2008” which is the date when I write this post.

Remember to use a pair of quotation mark if there are more than 1 parameter.

To have a date such as “day-month-year” – <?php echo date(“d-m-Y”); ?> we get “12-04-2008” which is the date when I write this post.

Not what you want? Try a Search

Add A Comment

*