You Kuper
You Kuper

Reputation: 1113

Transform DateTime variable into minutes

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?

Upvotes: 0

Views: 132

Answers (4)

Alfred Bratterud
Alfred Bratterud

Reputation: 533

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

Upvotes: 0

Glavić
Glavić

Reputation: 43552

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') );

Upvotes: 3

rationalboss
rationalboss

Reputation: 5389

$datetime = strtotime('2012-09-09 01:40');
$hour = date('H',$datetime);
$min = date('i',$datetime);
echo ($hour*60 + $min);

Upvotes: 0

David
David

Reputation: 3822

$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).

Upvotes: 1

Related Questions