I have a code where I have to "round" to the lowest minute.
16:05:00
should become 16:05:00
16:05:01
should become 16:05:00
16:05:29
should become 16:05:00
16:05:30
should become 16:05:00
16:05:31
should become 16:05:00
16:05:59
should become 16:05:00
I want to use the DateTime object. There are no functions such as:
setHours()
setMinutes()
setSeconds()
Here's the beginning of my code:
$my_date=DateTime::createFromFormat(
'Y-m-d H:i:s',
$bd_date
);
$my_date->setTimezone(self::$TimeZone);
Now I'd like to set the "seconds" part to zero.
Do you have an elegant way of only setting minutes the way I'd like to?
Nota: I'm not looking for a solution like "divide by getTime() by 60, convert to integer, then multiply by 60". I'm looking for a generic solution to set the seconds, not only to "0".
1 Answer. Show activity on this post. $timeFirst = strtotime('2011-05-12 18:20:20'); $timeSecond = strtotime('2011-05-13 18:20:20'); $differenceInSeconds = $timeSecond - $timeFirst; You will then be able to use the seconds to find minutes, hours, days, etc.
$min = $interval ->days * 24 * 60; $min += $interval ->h * 60; $min += $interval ->i; // Printing the Result in Minutes format.
The validateDate() function checks whether the given string is a valid date using PHP. It uses PHP DateTime class to validate date based on the specified format. This function returns TRUE if date string is valid, otherwise FALSE. $date – Required.
Is setTime elegant?
$my_date->setTime ( $my_date->format("H"), $my_date->format("i"), $new_second_val );
$my_date->setTime ( $my_date->format("H"), $new_minute_val, $new_second_val );
// etc...
Just set the seconds to "00"
date_default_timezone_set('America/Sao_paulo');
$date = new DateTime();
echo $date->format('Y-m-d H:i:00');
Best way to set the second/minute or hour by simply using the second/minute or hour function on Carbon DateTime Object. (obvious you will need to create carbon object)
\Carbon\Carbon::now()->hour(2)->minute(20)->second(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With