Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print the time an hour ago PHP?
To print time an hour ago in PHP, you need to subtract 1 hour from the current time. Use the strtotime() function with a relative time string like '-1 hour' to calculate the past time.
Syntax
date('format', strtotime('-1 hour'));
Example
Here's how to get the time exactly one hour ago ?
<?php
$oneHourAgo = date('Y-m-d H:i:s', strtotime('-1 hour'));
echo 'One hour ago, the date = ' . $oneHourAgo;
?>
One hour ago, the date = 2020-09-26 17:42:22
Multiple Hours Ago
You can calculate different hours by changing the value ?
<?php
echo "Current time: " . date('H:i:s') . "
";
echo "1 hour ago: " . date('H:i:s', strtotime('-1 hour')) . "
";
echo "2 hours ago: " . date('H:i:s', strtotime('-2 hours')) . "
";
echo "3 hours ago: " . date('H:i:s', strtotime('-3 hours')) . "
";
?>
Current time: 18:42:22 1 hour ago: 17:42:22 2 hours ago: 16:42:22 3 hours ago: 15:42:22
Using DateTime Class
Alternative approach using the modern DateTime class ?
<?php
$datetime = new DateTime();
$datetime->modify('-1 hour');
echo 'One hour ago: ' . $datetime->format('Y-m-d H:i:s');
?>
One hour ago: 2020-09-26 17:42:22
Conclusion
Use strtotime('-1 hour') with date() for simple calculations, or the DateTime class for more complex date operations. Both methods effectively calculate past times by subtracting hours from the current timestamp.
Advertisements
