-8

How can I hold in a data structure in PHP only the time of the day and the day of the week?

E.g.: 17:20 Sunday

Also I need to add minutes and hours to it.

E.g.: 22:03 Sunday + 03:00 = 01:03 Monday

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Radu Stanescu
  • 37
  • 1
  • 3
  • 10
  • You start by reading the manual. Here's "one" of them http://php.net/manual/en/function.date.php – Funk Forty Niner Jan 26 '15 at 14:31
  • Probaly the best way for this is to create a custom class – Bart Haalstra Jan 26 '15 at 14:34
  • 1
    I was able to recreate both of these cases in [phpfiddle](http://phpfiddle.org/) (an online PHP editor) in a little over 6 minutes using [`date()`](http://php.net/manual/en/function.date.php) and [`strtotime()`](http://php.net/manual/en/function.strtotime.php). Visit those links and give it a try in PHPFiddle. If you're still having trouble, post what you've tried and I'm sure people will be glad to help. According to the [help center](http://stackoverflow.com/help/on-topic) SO, usually addresses _"a specific programming problem"_. This question, in it's current form, is a little too broad. – War10ck Jan 26 '15 at 14:39
  • Well it was for a friend so i can't futher provide info unless I get some more from them... – Radu Stanescu Jan 26 '15 at 14:44
  • @RaduStanescu True, but again, you could visit the links and recreate the examples above using `date()`, `time()` and `strtotime()`. The documentation on these functions is exceptional. If you're able to recreate the examples then you'll be able to assist your friend. – War10ck Jan 26 '15 at 14:47

1 Answers1

-1

Untested and probably not the best way

class TimeWeekday {
    private $hour;
    private $minute;
    private $day;

    private $days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

    public function __construct($hour, $minute, $day) {
        $this->hour = $hour;
        $this->minute = $minute;
        $this->day = $day;
    }

    public function add($hours, $minutes, $days = 0) {
        $newMinutes = $this->minute + $minutes;
        $this->minute = $newMinutes % 60;
        if ($this->minute < 0) {
            $this->minute += 60;
        }
        $newHours = $this->hour + $hours + floor($newMinutes / 60);
        $this->hour = $newHours % 24;
        if ($this->hour < 0) {
            $this->hour += 24;
        }
        $newDay = $this->day + $days + floor($newHours / 60);
        $this->day = $newDay % 7;
        if ($this->day < 0) {
            $this->day += 7;
        }
    }

    public function substract($hours, $minurtes, $days = 0) {
        $this->add(-$hours, -$minurtes, -$days);
    }

    public function getValue() {
        return sprintf('%02d:%02d %s', $this->hour, $this->minute, $this->days[$this->day]);
    }
}

.

$x = new TimeWeekday(22, 3, 6);
$x->add(3,0);
echo $x->getValue();
Bart Haalstra
  • 1,062
  • 6
  • 11