John Davidson

Print php time in datetime format starting from last 5 minutes with range of every minute

0 comments
Message:


I need to print the start and end time of where the difference of start and end time in 1 minute. The fetching will start from the last 7th minutes until the last 2 minutes. That means the time from last five minutes. Here is the code I have written


$time = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
$time->setTimezone(new DateTimeZone('Asia/Dhaka'));

for($count = 5 ; $count >0 ; $count--){
$time_to_check = 0-($count+1);
$now = $time->modify($count.' minutes');
$now_check = $time->format("Y-m-d H:i:s.u");
$last_checked_time = $time->modify('-59 seconds');
$last_checked = $last_checked_time->format("Y-m-d H:i:s.u");

echo "start: ".$now_check."<br>";
echo "end: ".$last_checked."<br><br>";
}

for example, if the current time is 2021-03-03 22:26.416352


Expected output will be:


start: 2021-03-03 22:20:30.416352
end: 2021-03-03 22:21:29.416352

start: 2021-03-03 22:21:30.416352
end: 2021-03-03 22:22:29.416352

start: 2021-03-03 22:22:30.416352
end: 2021-03-03 22:23:29.416352

start: 2021-03-03 22:23:30.416352
end: 2021-03-03 22:24:29.416352

start: 2021-03-03 22:24:30.416352
end: 2021-03-03 22:25:29.416352

But i am getting the following output:


start: 2021-03-03 22:29:30.416352
end: 2021-03-03 22:28:31.416352

start: 2021-03-03 22:32:31.416352
end: 2021-03-03 22:31:32.416352

start: 2021-03-03 22:34:32.416352
end: 2021-03-03 22:33:33.416352

start: 2021-03-03 22:35:33.416352
end: 2021-03-03 22:34:34.416352

start: 2021-03-03 22:35:34.416352
end: 2021-03-03 22:34:35.416352

I am getting future time in my output and the difference is not 1 minute one from another. How can I do this efficiently? Thanks



My Answer:
You can achieve the desired output by modifying your code as follows:

php
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Asia/Dhaka'));

for ($count = 5; $count > 0; $count--) {
$now = clone $time;
$now->modify("-$count minutes");
$now_check = $now->format("Y-m-d H:i:s.u");

$last_checked = clone $now;
$last_checked->modify('+59 seconds');
$last_checked = $last_checked->format("Y-m-d H:i:s.u");

echo "start: $now_check
";
echo "end: $last_checked

";
}


This code will output the start and end times for the last 5 minutes with a difference of 1 minute between each pair. The `clone` keyword is used to create a copy of the DateTime object to avoid modifying the original object.

Rate this post

5 of 5 based on 1399 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us