FRED™  3.0
FRED™: Framework for Rapid and Easy Development
DateTime.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Rsi\Fred\DateTime;
4 
5 class DateTime extends \DateTime{
6 
7  public static function create($value,$format = null){
8  if(!$value) return null;
9  $value = parent::createFromFormat($format ?: 'Y-m-d H:i:s',$value);
10  if(!$value) return false;
11  $result = new static();
12  $result->setTimestamp($value->getTimestamp());
13  return $result;
14  }
15 
16  public function add($interval = 1){
17  if(is_numeric($interval)) $interval = 'P' . $interval . 'D';
18  if(is_string($interval)) $interval = new \DateInterval($interval);
19  parent::add($interval);
20  return $this;
21  }
22 
23  public function sub($interval = 1){
24  if(is_numeric($interval)) $interval = 'P' . $interval . 'D';
25  if(is_string($interval)) $interval = new \DateInterval($interval);
26  parent::sub($interval);
27  return $this;
28  }
29 
30  public function setDate($year,$month,$day){
31  parent::setDate($year ?: $this->year,$month ?: $this->month,$day ?: $this->day);
32  return $this;
33  }
34 
35  public function setTime($hour,$minute,$second = 0,$microseconds = 0){
36  parent::setTime(
37  $hour === null ? $this->hour : $hour,
38  $minute === null ? $this->minute : $minute,
39  $second === null ? $this->second : $second,
40  $microseconds === null ? $this->microseconds : $microseconds
41  );
42  return $this;
43  }
44 
45  public function __get($key){
46  $trim = false;
47  switch(rtrim($key,'s')){
48  case 'date': $key = 'Y-m-d'; break;
49  case 'year': $key = 'Y'; break;
50  case 'month': $key = 'n'; break;
51  case 'day': $key = 'j'; break;
52  case 'dayOfWeek': $key = 'w'; break;
53  case 'week': $key = 'o\\WW'; break;
54  case 'time': $key = 'H:i:s'; break;
55  case 'hour': $key = 'G'; break;
56  case 'minute': $key = 'i'; $trim = true; break;
57  case 'second': $key = 's'; $trim = true; break;
58  }
59  $value = $this->format($key);
60  return $trim ? (ltrim($value,'0') ?: 0) : $value;
61  }
62 
63  public function __set($key,$value){
64  $year = $month = $day = $hour = $minute = $second = null;
65  switch(rtrim($key,'s')){
66  case 'year': $year = $value; break;
67  case 'month': $month = $value; break;
68  case 'day': $day = $value; break;
69  case 'hour': $hour = $value; break;
70  case 'minute': $minute = $value; break;
71  case 'second': $second = $value; break;
72  default: throw new \DomainException("Undefined property '$key'");
73  }
74  if($year || $month || $day) $this->setDate($year,$month,$day);
75  if(($hour !== null) || ($minute !== null) || ($second !== null)) $this->setTime($hour,$minute,$second);
76  }
77 
78  public function __toString(){
79  return $this->format('Y-m-d H:i:s');
80  }
81 
82 }
setTime($hour, $minute, $second=0, $microseconds=0)
Definition: DateTime.php:35
static create($value, $format=null)
Definition: DateTime.php:7
setDate($year, $month, $day)
Definition: DateTime.php:30