Table of Contents

PHP Date and Time

Using the PHP date and time functions, we can get the current date, we can set a date, and we can do a different date and time manipulations and essentially display it in a nice format. So let's start off with our date function.

<!DOCTYPE html>
<html>
<head>
   <title>My First PHP App</titile>
</head>
<body>
  
  <?php echo date('m'); ?>

</body>
</html>

The date('m') function is going to show us the current month (11). You can also print out which day it is and which year it is. You can do everything at the same time.

 <?php echo date('m-d-Y'); ?>

This will print out the current month, date, and year (11-28-2020). There are different ways you can format the current date. You can give the capital F, which will provide us with the string representation of the current month November.

<?php echo date('F'); ?>

We can also say lowercase l, which will give us the current day of the week Saturday.

<?php echo date('l'); ?>

If you want to check more about these date functions, I would recommend you check out the this PHP documentation.

We can also display the current time.

<?php echo date('h:i:sa); ?>

With the h, we are showing the hour. With the i, we are showing the minute, and with the s, we are showing the seconds. The a is going to give us a representation of whether this is an a.m. or p.m.

You will notice that its not showing your time zone. It will be showing the UTC time zone by default which is the universal time zone. In most cases this is what PHP uses as default. But we can change that by changing the current time zone:

<?php date_default_timezone_set('America/Los_Angeles'); ?>
<?php echo date('h:i:sa); ?>

This will show us the America/Los Angeles time zone.