Clamping dates in PHP

Needed to clamp a unix timestamp in PHP so I could use it for a database lookup. Quick source dump as follows: –

$time = date_create()->getTimeStamp(); // Get the initial timestamp
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Before: " . $mysqlDateTime . "<br />";

// Clamp to Minutes
$time = floor($time / 60) * 60;
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Clamp to Minutes: " . $mysqlDateTime . "<br />";

// Clamp to Hours
$time = floor($time / 3600) * 3600;
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Clamp to Hours: " . $mysqlDateTime . "<br />";

// Clamp to Days
$time = floor($time / 86400) * 86400;
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Clamp to Days: " . $mysqlDateTime . "<br />";

This gives the output: –

Before: 2018-02-03 23:45:24
Clamp to Minutes: 2018-02-03 23:45:00
Clamp to Hours: 2018-02-03 23:00:00
Clamp to Days: 2018-02-03 00:00:00

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s