Reputation: 15796
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".
Upvotes: 21
Views: 28862
Reputation: 3180
$db = new DateTime();
$db->setTime($db->format('H'), $db->format('i'), 0);
$currentMinute = $db->format('Y-m-d H:i:s');
Upvotes: 0
Reputation: 1
from docs should be
$dt = Carbon::create(2012, 1, 31, 15, 32, 45);
echo $dt->startOfMinute(); // 2012-01-31 15:32:00
Upvotes: 0
Reputation: 3240
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);
Upvotes: 3
Reputation: 745
I know this is a late answer but it might help someone the way it helped me.
You can add the first line if you need a specific timezone
date_default_timezone_set('Africa/Johannesburg');
$created = date('Y-m-d H:i:00', time());
Upvotes: 2
Reputation: 8062
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...
Upvotes: 51
Reputation: 4219
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');
Upvotes: 13