Given a Unix timestamp, how to get beginning and end of that day?

You can use the strtotime() function in PHP to convert a Unix timestamp to the beginning and end of that day.

To get the beginning of the day, you can use the strtotime() function to convert the timestamp to the start of the day (midnight) by passing in "midnight" or "today" as the second argument:

<?php

$timestamp = time(); // Use the current time, or replace with your own timestamp

// Calculate the beginning of the day
$beginning_of_day = strtotime("midnight", $timestamp);

// Format and output the beginning of the day
echo date("Y-m-d H:i:s", $beginning_of_day);

// Output: [current year]-[current month]-[current day] 00:00:00

?>

Watch a course Learn object oriented PHP

To get the end of the day, you can use the strtotime() function to convert the timestamp to the end of the day (23:59:59) by passing in "tomorrow" as the second argument and subtracting 1 second:

<?php

$timestamp = time(); // Use the current time, or replace with your own timestamp

// Calculate the end of the day
$end_of_day = strtotime("tomorrow", $timestamp) - 1;

// Format and output the end of the day
echo date("Y-m-d H:i:s", $end_of_day);

// Output: [current year]-[current month]-[current day] 23:59:59

?>

You can also use the date() function to format the timestamp to a specific format.

<?php

$timestamp = time(); // Use the current time, or replace with your own timestamp

// Calculate the beginning of the day
$beginning_of_day = date('Y-m-d H:i:s', strtotime("midnight", $timestamp));

// Calculate the end of the day
$end_of_day = date('Y-m-d H:i:s', strtotime("tomorrow", $timestamp) - 1);

// Output the beginning and end of the day
echo "Beginning of day: " . $beginning_of_day . "\n";
echo "End of day: " . $end_of_day . "\n";

// Output:
// Beginning of day: [current year]-[current month]-[current day] 00:00:00
// End of day: [current year]-[current month]-[current day] 23:59:59

?>