Olivier Pons
Olivier Pons

Reputation: 15796

Php: DateTime: how to set only seconds (not hours neither minutes)

I have a code where I have to "round" to the lowest minute.

I want to use the DateTime object. There are no functions such as:

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

Answers (6)

Sadee
Sadee

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

mapino
mapino

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

Sachin Kumar
Sachin Kumar

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

King Of The Jungle
King Of The Jungle

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

wroniasty
wroniasty

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

Eduardo Russo
Eduardo Russo

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

Related Questions