TimesCoding

Learn, Practice, and Excel with our Coding Tutorials!

PHP Date and Time Functions Explained with Examples

June 20, 2024 3 Min read PHP

PHP offers a variety of functions for working with dates and times. These functions allow you to:

  • Get the current date and time
  • Format dates and times in different ways
  • Parse human-readable dates into timestamps (seconds since the Unix Epoch)
  • Perform calculations on dates and times

Here are some commonly used functions and examples:

Getting the Current Date and Time

PHP’s date() function is commonly used to get the current date and time. The function takes a format string as a parameter and returns a formatted date string.

<?php
echo date('Y-m-d H:i:s');    //Output: 2024-06-17 14:35:12
?>
  • Y: Four-digit year
  • m: Two-digit month
  • d: Two-digit day
  • H: Two-digit hour (24-hour format)
  • i: Two-digit minutes
  • s: Two-digit seconds

Custom Formatting

You can customize the date and time format by using different characters in the format string.

<?php
echo date('l, F j, Y g:i A');    //Output: Monday, June 17, 2024 2:35 PM
?>
  • l: Full weekday name
  • F: Full month name
  • j: Day of the month without leading zeros
  • Y: Four-digit year
  • g: Hour (12-hour format) without leading zeros
  • A: Uppercase AM/PM

Working with Timestamps

The time() function returns the current Unix timestamp, the number of seconds since January 1, 1970 (UTC).

<?php
echo time();    //Output: 1718644512
?>

To convert a timestamp into a readable date, use the date() function.

<?php
$timestamp = time();
echo date('Y-m-d H:i:s', $timestamp);    //Output: 2024-06-17 13:45:33
?>

Creating Dates with mktime()

The mktime() function allows you to create a Unix timestamp for a specific date and time.

<?php
$timestamp = mktime(14, 30, 0, 6, 17, 2024);
echo date('Y-m-d H:i:s', $timestamp);   //Output: 2024-06-17 14:30:00
?>

Using strtotime()

The strtotime() function parses an English textual datetime description into a Unix timestamp.

<?php
$timestamp = strtotime('next Monday');
echo date('Y-m-d H:i:s', $timestamp);   //Output: 2024-06-24 00:00:00
?>

Formatting Date and Time with DateTime Class

The DateTime class provides a more flexible and object-oriented way to work with dates and times.

<?php
$date = new DateTime();
echo $date->format('Y-m-d H:i:s');   //Output: 2024-06-17 14:35:12
?>

Modifying Dates

You can modify dates easily with the DateTime class.

<?php
$date = new DateTime('2024-06-17');
$date->modify('+1 day');
echo $date->format('Y-m-d');   //Output: 2024-06-18
?>

Additional Functions:

  • date_add(): Adds a specified interval (e.g., 1 day, 1 month) to a DateTime object.
  • date_diff(): Calculates the difference between two DateTime objects.
  • gmdate(): Similar to date() but uses GMT (Greenwich Mean Time).
  • checkdate(): Validates a Gregorian calendar date.
Related Post:
CSRF vs XSS: Key Differences and How to Prevent Attacks − For web security, CSRF (Cross-Site Request Forgery) and XSS (Cross-Site Scripting) both are potent vulnerabilities that can wreak havoc if exploited, but they are fundamentally.
How to Use PHP iconv() Function for Effective Character Encoding Conversion − The iconv() function in PHP is used for character set conversion. This function converts a string from one character encoding to another. It is particularly.
How to Use the PHP chr() Function with Examples − The chr() function in PHP is used to return a character from a specified ASCII value. ASCII (American Standard Code for Information Interchange) values range.
How to Use PHP chunk_split() Function for String Manipulation − PHP chunk_split() Function The chunk_split() function in PHP is used to split a string into smaller chunks and add a specified string (usually a separator).
How to Use the PHP chop() Function to Trim Strings Effectively − The chop() function in PHP is used to remove whitespace or other predefined characters from the right end of a string. It’s an alias for.
How to Share Session Variables Between PHP Files for Secure CSRF Token Handling − In this tutorial, we will learn how to share session variables between PHP files, specifically focusing on handling a CSRF (Cross-Site Request Forgery) token securely..
PHP and MySQL Connection: MySQLi vs PDO Explained − Connecting PHP to MySQL is a common task in web development. Below are the steps to establish a connection using the MySQLi (MySQL Improved) extension.
PHP bin2hex() Function with Example − The bin2hex() function in PHP converts binary data into its hexadecimal representation. This can be particularly useful for encoding binary data in a readable format.
Secure Your PHP Strings with the addslashes() Function − The addslashes() function in PHP is used to escape certain characters in a string by adding backslashes before them. This is particularly useful when preparing.
PHP Sanitize Input with Example: Keeping Your Website Secure − In the dynamic world of web development, user input is the lifeblood of many applications. However, this very input can also pose a significant security.
Creating a Mobile Number Show-Hide Feature with HTML, CSS, and PHP − In today’s web development landscape, creating a user-friendly and secure user interface is crucial. One common requirement is the need to display sensitive information, such.
URL Exist or Not Exist Check PHP − We can easily check a given URL or Link is active or not. By using below PHP function we can easily get whether the given.