0

There is the following variable:

$datetime = '2012-09-09 01:40';

I need to extract hours and minutes, and then to transform them into minutes. In this example, I would need to get 100 (1 hr 40 min = 60 min + 40 min). How can I quickly do this using PHP functions?

You Kuper
  • 1,113
  • 7
  • 18
  • 38

4 Answers4

3

The strtotime() and date() functions are not recommended anymore. Use the DateTime class.

$datetime = '2012-09-09 01:40';
$d = new DateTime($datetime);
var_dump( $d->format('G') * 60 + $d->format('i') );
Glavić
  • 42,781
  • 13
  • 77
  • 107
  • Why not? His date string is in standard format, and object declarations, from what I understand, are expensive. I still gave an upvote, because if he had dynamic strings, then he should use `DateTime`, no question. – David Sep 09 '12 at 17:26
  • 2
    @David: because your example won't work anymore if input will be year 2038 or bigger. try to set year to 2060 in your answer, and see what the output will be... – Glavić Sep 09 '12 at 17:32
  • 2
    Also: [DateTime class vs. native PHP date-functions](http://stackoverflow.com/q/8605563/612202) – dan-lee Sep 09 '12 at 17:39
1
$string = '2012-09-09 01:40';
$epoch = strtotime($string);
echo date('i', $epoch) + (60 * date('H', $epoch));

Outputs 100

Basically what happens here is the string date gets converted to Unix/Epoch time. Then, using date() it adds the number of minutes (i) to 60 times the number of hours (h).

David
  • 3,831
  • 2
  • 28
  • 38
0
$datetime = strtotime('2012-09-09 01:40');
$hour = date('H',$datetime);
$min = date('i',$datetime);
echo ($hour*60 + $min);
rationalboss
  • 5,330
  • 3
  • 30
  • 50
0

You can use preg_split like this:

$parts=preg_split("/(\d\d):(\d\d)/",$datetime,-1,PREG_SPLIT_DELIM_CAPTURE);
$mins=($parts[1]*60)+$parts[2];

Now $mins=100 when $datetime is like in your post

Alfred Bratterud
  • 523
  • 1
  • 4
  • 12