In this tutorial you will learn how to set the timezone in a PHP program and how to store and display the current date and time like what you see below.
There are a range of different timezones you can use in PHP as well as date/time formats. The links below provide a list of timezones and date/time formats in the PHP manual:
Watch the video below and then scroll down to see the sample code from the video as well as a table containing the most commonly used date/time formats.
Sample PHP code:
<?php // set timezone date_default_timezone_set('Australia/Sydney'); // display the date and time with a greeting function show_date(){ return date('l, jS F H:i'); } function greeting(){ $hour = date('H'); if($hour < 12){ $greeting = "Good morning!"; } else{ $greeting = "Good day!"; } return $greeting; } echo show_date(); echo "<br/>" . greeting(); ?>
List of commonly used date/time formats:
Argument | Description | Example |
Y | Year displayed as 4 digits | 2016 |
y | Year displayed as 2 digits | 16 |
n | Month displayed as 1 or 2 digits | 9 |
m | Month displayed as 2 digits | 09 |
F | Full name of the month | December |
M | Name of the month as 3 letters | Dec |
j | Day displayed as 1 or 2 digits | 3 |
d | Day displayed as 2 digits | 03 |
l | Full name of the weekday | Thursday |
D | First three letters of weekday | Thu |
S | Ordinal suffix displayed as 2 letters | eg. rd or th or nd |
H | Hour in 24hr time | 17 |
h | Hour in 12hr time | 5 |
i | Minutes | 30 |
s | Seconds | 50 |
a | am/pm lowercase | am |
A | AM/PM uppercase | PM |