Skip to content

Instantly share code, notes, and snippets.

@trq
Created August 10, 2014 07:20
Show Gist options
  • Save trq/1e6bb1c29589ccc900a6 to your computer and use it in GitHub Desktop.
Save trq/1e6bb1c29589ccc900a6 to your computer and use it in GitHub Desktop.
<?php
class TimePeriod
{
protected $periodRepresentation;
protected function __construct($periodRepresentation)
{
$this->periodRepresentation = $periodRepresentation;
}
public static function asMinutes($periodRepresentation)
{
return (new static($periodRepresentation))->parse();
}
public static function asHours($periodRepresentation)
{
$minutes = (new static($periodRepresentation))->parse();
return round($minutes / 60, 2);
}
public static function asDays($periodRepresentation)
{
$minutes = (new static($periodRepresentation))->parse();
return round(($minutes / 60) / 24, 2);
}
public static function asWeeks($periodRepresentation)
{
$minutes = (new static($periodRepresentation))->parse();
return round((($minutes / 60) / 24) / 7, 2);
}
protected function toMinutes($amount, $type)
{
switch ($type) {
case 'w':
$expression = 7 * 24 * 60;
break;
case 'd':
$expression = 24 * 60;
break;
case 'h':
$expression = 60;
break;
case 'm':
$expression = 1;
break;
}
return $expression * $amount;
}
protected function parse()
{
$minutes = 0;
$periodRepresentations = explode(' ', $this->periodRepresentation);
foreach ($periodRepresentations as $periodRepresentation) {
if (preg_match('/([0-9]*)(w|d|h|m){1}/', $periodRepresentation, $matches)) {
$minutes += $this->toMinutes($matches[1], $matches[2]);
}
}
return $minutes;
}
}
echo TimePeriod::asMinutes('7d 12h 30m') . "\n";
echo TimePeriod::asHours('7d 12h 30m') . "\n";
echo TimePeriod::asDays('7d 12h 30m') . "\n";
echo TimePeriod::asWeeks('7d 12h 30m');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment