Back

Exploring PHP Date Format

Almost every web application you use nowadays involves dates. Social media is one of the most common examples. When you post an image, an upload date is associated with it. Learning how to use date functions is very useful when building real-world applications, and in this tutorial, we’ll learn how to do it using PHP.

Introduction

We can format date with PHP by using the date() function.

Date function accepts two parameters :

  1. Format – This defines how you want your date to appear. For example, “Y-m-d” shows your date as Year – Month – Date.
  2. Timestamp – This is the time that you want the date to show. This is nullable and will show the current date by default.

This is an example of how you use the date format. The example below is the standard format you use when storing dates into MySQL.

$today = date("Y-m-d H:i:s");
echo $today; //2023-05-25 10:30:59

Another function that is really helpful is strtotime(). It converts the string into a time format. It is especially helpful when you want to format a date from database if combined with the date function.

$dateFromString = strtotime('2020-05-24 12:00:24');
$formatedDate = date('l jS \of F Y h:i:s A', $dateFromString);
echo $formatedDate; // Sunday 24th of May 2020 12:00:24 PM

That’s how you can get the current time and date, convert it into the format you want and also convert a string into time.
For complete list of what you can do with date function, you can visit the documentation.
Now, let’s look at some use cases where we can use date.

Case 1 : Timestamp to show when a record was created or updated

When you insert a record into database, generally you want a timestamp associated with it to mark when it is added or updated.

For example, let’s create this table in your database.

CREATE TABLE posts (
    id int PRIMARY KEY AUTO_INCREMENT,
    title varchar(255),
    created_at DATETIME,
    updated_at DATETIME
);

Now you have a table structure that looks like this

Prepare connect.php

<?php
	$username  = 'root';
	$password = '';
    $dbname = 'php_date';
	try {
		$connection = new PDO('mysql:host=localhost;dbname='.$dbname.';',$username,$password);
		$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
	}catch (PDOException $e) {
		print "Connection error : " . $e->getMessage() . "<br/>";
		die();
	}
?>

Make create.php

To add a timestamp to a post, we will insert the code below into the database and it will automatically get the current date and time. We format it as below since it is the date format in MySQL.

date("Y-m-d H:i:s")

Here is the full create.php code. We’re basically making a form without the date fields. We’ll be filling the dates automatically with the php date function.
If you want to learn more about the insert process (more explanation on the syntax and process), read my CRUD tutorial.

📌 Tip: PHP uses the server’s default timezone, which may differ depending on where your server is hosted. To ensure consistency when working with dates and times, you should set the timezone explicitly at the beginning of your PHP files using:

<?php
date_default_timezone_set('UTC'); // or your preferred timezone like 'America/New_York'
include('connect.php'); 

// if form is not empty
if(!empty($_POST)){
    // retrieving data from form
    $title = $_POST['title'];
    $created_at = date("Y-m-d H:i:s");
    $updated_at = null;
    
    $sql = 'INSERT INTO posts (title,created_at,updated_at) VALUES (?,?,?)';
    $row = $connection->prepare($sql);
    $row->execute([$title, $created_at, $updated_at]);

    // redirect to index
    echo '<script> alert("Post added"); window.location="index.php" </script>';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create</title>
</head>
<body>
    <h1>Create Post</h1>

    <form action="create.php" method="post">
        <label for="title">Title</label>
        <input type="text" name="title" placeholder="Learn PHP" id="title" required> <br>
        <input type="submit" value="Create">
    </form>
</body>
</html>

To edit the timestamp, we just have to update the title and the updated_at value. We don’t need to edit created_at.

<?php 
include('connect.php');

// retrieving the data by id
$id_get = $_GET['id'];
$sql = "SELECT * FROM posts WHERE id=?";
$row = $connection->prepare($sql);
$row->execute([$id_get]);
$post = $row->fetch();

// if form is not empty
if(!empty($_POST)){
    // retrieving data from form
    $id = $_POST['id'];
    $title = $_POST['title'];
    $updated_at = date("Y-m-d H:i:s");
        
    $sql = 'UPDATE posts SET title=?, updated_at=? WHERE id=?';
    $row = $connection->prepare($sql);
    $row->execute([$title, $updated_at, $id]);
    
    // redirect to index
    echo '<script> alert("Post edited"); window.location="index.php" </script>';
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit</title>
</head>
<body>
    <h1>Edit Post</h1>

    <form action="edit.php" method="post">
        <input type="hidden" name="id" id="id" value="<?php echo $post['id'];?>">
        <label for="title">Title</label>
        <input type="text" name="title" placeholder="Learn PHP" id="title" require value="<?php echo $post['title'];?>"> <br>
        <input type="submit" value="Update">
    </form>
</body>
</html>

Then, we can show the dates in index.php. In the example, I showed updated_at as it is while I formatted created_at to show the formatting capabilities of date function.

<?php include('connect.php'); ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Case 1</title>
</head>
<body>

<h1>Posts</h1>

<a href="create.php">Create New Post</a>

<table border="1">
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Created At</th>
            <th>Updated At</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    <?php
        // retrieving data from database
        $sql = "SELECT * FROM posts";
        $row = $connection->prepare($sql);
        $row->execute();
        $posts = $row->fetchAll();
        // showing the data with a loop
        foreach($posts as $post){
    ?>
    <tr>
        <td><?php echo $post['id']; ?></td>
        <td><?php echo $post['title']; ?></td>
        <td><?php echo date("l jS \of F Y h:i:s A", strtotime($post['created_at'])); ?></td>
        <td><?php echo $post['updated_at']; ?></td>
        <td>
            <a href="edit.php?id=<?php echo $post['id'];?>">Edit</a>
        </td>
    </tr>
    <?php
        }
    ?>
    </tbody>
</table>
</body>
</html>

This is an example of the posts table. You can see the different format between created_at and updated_at.

Case 2 : Saving a start and end date in the database

In the previous case, we automatically saved the date without choosing it. But, what about when we want to choose the date manually. For example, when we’re making an event scheduler. We can use the date picker.

Let’s prepare another table for it.

CREATE TABLE events (
    id int PRIMARY KEY AUTO_INCREMENT,
    event_name varchar(255),
    start DATE,
    end DATE
);

And this is the code to add event and choose dates. We’ll be using HTML input tags with datae as the type. It saves the date you inputted as a string, so you have to convert it with strtotime() and then insert it into the database.

<?php 
include('connect.php'); 

// if form is not empty
if(!empty($_POST)){
    // retrieving data from form
    $event_name = $_POST['event_name'];
    $start = date('Y-m-d', strtotime($_POST['start']));
    $end = date('Y-m-d', strtotime($_POST['end']));
    
    $sql = 'INSERT INTO events (event_name,start,end) VALUES (?,?,?)';
    $row = $connection->prepare($sql);
    $row->execute([$event_name, $start, $end]);

    // redirect to index
    echo '<script> alert("Event added"); window.location="index.php" </script>';
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event</title>
</head>
<body>
    <h1>Create Event</h1>

    <form action="index.php" method="post">
        <label for="event_name">Event</label>
        <input type="text" name="event_name" placeholder="Concert" id="event_name" require> <br>
        <label for="start">Start</label>
        <input type="date" name="start" id="start"> <br>
        <label for="end">End</label>
        <input type="date" name="end" id="end"> <br>
        <input type="submit" value="Create">
    </form>
</body>
</html>

This is how it looks after the database is inserted.

Case 3 : How to calculate time between two dates

There are cases where we need to count the time between two dates, this is how we can do it.

If we have the right date format, we can directly subtract them from each other. That will give us the time difference in seconds. You can divide itu by 60 or by 3600 if you want it in minutes or hours. Now you know the basic to count the time difference, you can explore to find how to show it in days or in hours-minutes-seconds format.

<?php
function calculateTimeBetweenDates($start,$end){
    $startTime = strtotime($start);
    $endTime = strtotime($end);
    $timeBetween = abs($endTime - $startTime);
    return $timeBetween;
}
$timeInSeconds = calculateTimeBetweenDates('2023-05-23 12:00:24','2023-05-24 12:00:24'); // raw seconds
$timeInMinutes = $timeInSeconds/60;
$timeInHours = $timeInMinutes/60;
echo $timeInSeconds.'<br>'; //86400
echo $timeInHours; //24
?>

That’s how you can calculate the time. You can explore more by providing a User Interface to input the time and date.

Conclusion

That’s how you can use date functions in PHP. I’ve kept the tutorial practical with some use cases. That should be enough for you to start using it. As a closing statement, if you need more information in date functions, you can always rely on the documentation.

Dev Noob
Dev Noob