PHP gmdate() Tutorial

beginner
20 min

PHP gmdate() Tutorial

Welcome to our comprehensive PHP gmdate() tutorial! In this lesson, we'll explore how to work with dates and time in PHP using the gmdate() function. By the end of this tutorial, you'll be able to manipulate dates and times with ease, making you ready to tackle real-world projects. 🎯

What is gmdate()?

In PHP, the gmdate() function is used to convert a Unix timestamp or a date in a specific format into a readable date and time. The "gm" in gmdate() stands for Greenwich Mean Time (GMT), making it ideal for working with Coordinated Universal Time (UTC). πŸ“

Basic Usage

Let's dive into a simple example to understand how the gmdate() function works:

php
<?php $timestamp = time(); // Get the current timestamp echo gmdate("F j, Y", $timestamp); // Output the current month, day, and year in long format ?>

In the above example, we're getting the current timestamp using the time() function and then converting it to a readable date format using gmdate(). The format string "F j, Y" will output the current month, day, and year in long format. βœ…

Understanding Format Strings

Format strings in gmdate() allow you to control the output format of the date and time. Here's a list of some commonly used format characters:

  • F - Full month name
  • j - Day of the month without leading zeros
  • Y - Four-digit year
  • H - Hour (24-hour clock) with leading zeros
  • i - Minutes with leading zeros
  • s - Seconds with leading zeros

You can find a complete list of format characters in the PHP Date and Time User Guide. πŸ“

Practical Example

Now let's create a simple PHP script that displays the current date and time in a specific format for a website footer:

php
<?php $date_and_time = gmdate("l, F jS Y \a\t H:i:s"); echo "Last updated on: " . $date_and_time; ?>

In this example, we're using the format string "l, F jS Y \a\t H:i:s" to output the day of the week, month, day of the month (with a leading zero if needed), year, a tab character, hour, minute, and second of the current date and time. βœ…

Working with Timestamps

Besides working with the current date and time, you can also use the gmdate() function to work with custom timestamps:

php
<?php $timestamp = strtotime("January 1, 2000"); // Set a custom timestamp echo gmdate("F j, Y", $timestamp); // Output the date in long format ?>

In the above example, we're creating a custom timestamp for January 1, 2000, using the strtotime() function, and then converting it to a readable date format using gmdate(). βœ…

Quiz

Quick Quiz
Question 1 of 1

What does the "g" in `gmdate()` stand for?


By now, you should have a solid understanding of the PHP gmdate() function and how to use it in your projects. Remember to be patient and practice as you continue to learn and grow your PHP skills. Happy coding! 😊