Set the Date using PHP

Hello all, I apologize for not posting for awhile, I switched positions and it took some time to get settled into my new job. I hope everyone had a great holidays and had a safe and happy new year celebration!

Now, back to coding. Today I will talk about a very basic PHP technique that is very useful in any website or application that you will be including the current date. If the date is meant to be updated every day, month, or year, using HTML to include this is not very useful, as it will need to be manually updated everyday.

However, using PHP, the date on your webpage will automatically update everyday with the current date making less work for the developer while keeping your website current.

In order to include PHP in your webpage, you must open a PHP tag:

<?php

//PHP code goes in this area

?>

Inside the PHP tags, before you set the date, you should set the timezone you want the date to pull from. This is not required, but without it, you will get a warning and run the risk of not having the correct date.

This appears as follows:

<?php

date_default_timezone_set("America/New_York");

?>

Set the timezone string as the desired country/desired state or territory. for a full list of acceptable timezones, visit PHP List of Supported Timezones.

Next, we must add the display of our date. This will reference the set timezone, and display the correct date for the day the webpage is accessed.

<?php

date_default_timezone_set("America/New_York");

echo date("m.d.Y");

?>

Using the echo function, we display the date in mm.dd.yyyy format. I can be displayed in any format:

ex. mm/dd/yyyy , dd-mm-yyyy ,  etc. using any separator desired and in any desired order.

Using this small piece of PHP code, you can display the current date on your webpage without doing any extra work. Thank you for reading, I hope you found this tutorial useful!

Advertisements