PHP MySQL Select Hour from Timestamp Example

Feb 25, 2022 . Admin

Hello Friends,

I am going to explain you example of PHP select hour from timestamp example. You will learn PHP - search timestamp by hour of day. In side this article we will see the PHP - extract HOUR from DATETIME / TIMESTAMP / TIME.

This article will give you simple example of how to display only hour and minutes in PHP?. We will use get search how to find the PHP get date difference in hours code example.

You can use from PHP to display day hour from timestamp. I will give you simple query to getting data get the hour from table.

Table: users


So, let's see bellow solution:

index.php
<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "db_php";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT 
            id, 
            name, 
            email, 
            TIME_FORMAT(created_at, '%H:%i:%s') as time,
            TIME_FORMAT(created_at, '%H') as hour,
            TIME_FORMAT(created_at, '%i') as minute,
            TIME_FORMAT(created_at, '%s') as second
        FROM `users`";

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    echo '<pre>';
    print_r($row);
}

?>
Output:
Array
(
    [id] => 1
    [name] => Divyesh Barad
    [email] => divyeshbarad@gmail.coim
    [time] => 13:23:20
    [hour] => 13
    [minute] => 23
    [second] => 20
)
Array
(
    [id] => 2
    [name] => Aatman Infotech
    [email] => aatmaninfotech@gmail.com
    [time] => 10:27:34
    [hour] => 10
    [minute] => 27
    [second] => 34
)
Array
(
    [id] => 3
    [name] => Haresh 
    [email] => savani@gmail.com
    [time] => 01:25:28
    [hour] => 01
    [minute] => 25
    [second] => 28
)
It will help you...
#PHP