Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

datetime

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".

like image 354
Olivier Pons Avatar asked Jun 27 '12 10:06

Olivier Pons


People also ask

How will you get the difference between 2 DateTime values in seconds in PHP?

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.

How can I get minutes in PHP?

$min = $interval ->days * 24 * 60; $min += $interval ->h * 60; $min += $interval ->i; // Printing the Result in Minutes format.

Is DateTime valid in PHP?

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.


3 Answers

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...
like image 128
wroniasty Avatar answered Oct 11 '22 12:10

wroniasty


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');
like image 42
Eduardo Russo Avatar answered Oct 11 '22 12:10

Eduardo Russo


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);
like image 3
Sachin Kumar Avatar answered Oct 11 '22 13:10

Sachin Kumar