├── .gitignore ├── composer.json ├── README.md ├── LICENSE └── TimeHelper.php /.gitignore: -------------------------------------------------------------------------------- 1 | # Файлы настроек редакторов и IDE 2 | .project 3 | .settings 4 | .vimrc 5 | .idea 6 | /nbproject/* -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "korytoff/timehelper", 3 | "description": "Php class helper for formatting datetime", 4 | "version": "1.3", 5 | "authors": [ 6 | { 7 | "name": "korytoff", 8 | "email": "korytoff@gmail.com" 9 | } 10 | ], 11 | "minimum-stability": "dev", 12 | "require": { 13 | "php": ">=5.4.0" 14 | }, 15 | "autoload": { 16 | "psr-0": { 17 | "korytoff/helpers/timehelper": "/TimeHelper.php" 18 | } 19 | }, 20 | "support": { 21 | "source": "https://github.com/korytoff/PHP-TimeHelper" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Code Climate](https://codeclimate.com/github/korytoff/PHP-TimeHelper/badges/gpa.svg)](https://codeclimate.com/github/korytoff/PHP-TimeHelper) 2 | 3 | Php TimeHelper class 4 | ============== 5 | 6 | Php class helper for formatting datetime 7 | 8 | Download file and install 9 | ----------- 10 | ```php 11 | 14 | ``` 15 | 16 | Or use composer 17 | ----------- 18 | ```json 19 | { 20 | "repositories": [ 21 | ... 22 | { 23 | "type": "git", 24 | "url": "https://github.com/korytoff/PHP-TimeHelper.git" 25 | } 26 | ], 27 | "require": { 28 | ... 29 | "korytoff/helpers/timehelper": "*" 30 | }, 31 | } 32 | ``` 33 | 34 | ```bash 35 | $ php composer.phar update 36 | ``` 37 | 38 | Use 39 | ----------- 40 | ```php 41 | today(); // Сегодня, Завтра, Вчера или 14 сентября 2015 г. 43 | ?> 44 | ``` 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 korytoff 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /TimeHelper.php: -------------------------------------------------------------------------------- 1 | datetime(); 133 | } 134 | 135 | /** 136 | * Клонирование 137 | */ 138 | public function __clone() 139 | { 140 | $this->_dateTime = clone $this->_dateTime; 141 | } 142 | 143 | /** 144 | * @param null $date 145 | * @param string $format 146 | */ 147 | function __construct($date = null, $format = self::DATETIME) 148 | { 149 | mb_internal_encoding('UTF-8'); 150 | if ($format === self::STRDATE) { 151 | $this->_dateTime = $this->parse($date); 152 | } elseif (is_string($date)) { 153 | $this->_dateTime = \DateTime::createFromFormat($format, $date); 154 | } elseif (is_a($date, 'DateTime')) { 155 | $this->_dateTime = $date; 156 | } else { 157 | $this->_dateTime = new \DateTime; 158 | } 159 | 160 | return $this; 161 | } 162 | 163 | /** 164 | * Разбор даты из строки вида '2 Мая 2014 в 12:05' 165 | * 166 | * @param $str 167 | * @return \DateTime 168 | */ 169 | public function parse($str) 170 | { 171 | $str = mb_strtolower(trim($str)); 172 | preg_match('/^(\d+) +([ъхзщшгнекуцйфывапролджэёюбьтимсчя]+) +(\d{4})[A-zА-я ]+(\d{2}:?\d?\d?)?/', $str, $matches); 173 | $result['day'] = (isset($matches[1]) && is_numeric($matches[1])) ? str_pad($matches[1], 2, '0', STR_PAD_LEFT) : date('d'); 174 | if (isset($matches[2])) { 175 | $month = array_map('mb_strtolower', $this->month); 176 | $monthPlural = array_map('mb_strtolower', $this->monthPlural); 177 | $shortMonth = array_map('mb_strtolower', $this->shortMonth); 178 | if (array_keys($month, $matches[2])) { 179 | $monthNum = array_keys($month, $matches[2]); 180 | } elseif (array_keys($monthPlural, $matches[2])) { 181 | $monthNum = array_keys($monthPlural, $matches[2]); 182 | } elseif (array_keys($shortMonth, $matches[2])) { 183 | $monthNum = array_keys($shortMonth, $matches[2]); 184 | } 185 | } 186 | $result['month'] = isset($monthNum[0]) ? str_pad($monthNum[0] * 1 + 1, 2, '0', STR_PAD_LEFT) : date('m'); 187 | $result['year'] = (isset($matches[3]) && strlen($matches[3]) === 4) ? $matches[3] : date('Y'); 188 | $result['time'] = isset($matches[4]) ? str_pad($matches[4], 8, ':00') : "00:00:00"; 189 | $dateStr = $result['year'] . '-' . $result['month'] . '-' . $result['day'] . ' ' . $result['time']; 190 | 191 | return $result ? \DateTime::createFromFormat(self::DATETIME, $dateStr) : new \DateTime; 192 | } 193 | 194 | /** 195 | * Прибавление дней 196 | * 197 | * @param int $day 198 | * @return $this 199 | */ 200 | public function plusDay($day = 1) 201 | { 202 | $this->_dateTime->modify("+$day day"); 203 | 204 | return $this; 205 | } 206 | 207 | /** 208 | * Изменение даты 209 | * 210 | * @param $day 211 | * @param string $param 212 | * @return $this 213 | */ 214 | public function modify($day, $param = 'day') 215 | { 216 | $day = (int) $day; 217 | $this->_dateTime->modify("$day $param"); 218 | 219 | return $this; 220 | } 221 | 222 | /** 223 | * Вывод даты и времени с указанием формата 224 | * 225 | * @param bool|true $time 226 | * @param string $dateFormat 227 | * @return string 228 | */ 229 | public function datetime($time = true, $dateFormat = self::DATE) 230 | { 231 | $result = ''; 232 | switch ($dateFormat) { 233 | case self::DATETIME: 234 | case self::EUR_DATETIME: 235 | $time = false; 236 | break; 237 | default: 238 | break; 239 | } 240 | if ($this->_dateTime) { 241 | $result .= $this->_dateTime->format($dateFormat); 242 | if ($time) { 243 | $result .= ' ' . $this->_dateTime->format('H:i:s'); 244 | } 245 | } 246 | 247 | return $result; 248 | } 249 | 250 | /** 251 | * Получение номера дня 252 | * 253 | * @return string 254 | */ 255 | public function day() 256 | { 257 | $result = ''; 258 | $result .= (int) $this->_dateTime->format('j'); 259 | 260 | return $result; 261 | } 262 | 263 | /** 264 | * Получения номера дня недели 265 | * 266 | * @return int 267 | */ 268 | public function dayOfWeek() 269 | { 270 | return (int) $this->_dateTime->format('N'); 271 | } 272 | 273 | /** 274 | * Получение дня недели текстом 275 | * 276 | * @param bool|false $short 277 | * @return string 278 | */ 279 | public function dayStr($short = false) 280 | { 281 | $N = (int) $this->_dateTime->format('N') - 1; 282 | $days = ($short) ? $this->shortDay : $this->day; 283 | return isset($days[$N]) ? $days[$N] : ""; 284 | } 285 | 286 | /** 287 | * Получение недели 288 | * 289 | * @param bool|true $plural 290 | * @return string 291 | */ 292 | public function month($plural = true) 293 | { 294 | $result = ''; 295 | $M = (int) $this->_dateTime->format('n') - 1; 296 | if ($plural) { 297 | $result .= ' ' . mb_convert_case($this->monthPlural[$M], MB_CASE_TITLE); 298 | } else { 299 | $result .= ' ' . mb_convert_case($this->month[$M], MB_CASE_TITLE); 300 | } 301 | 302 | return $result; 303 | } 304 | 305 | /** 306 | * Разница с текущей датой и временем 307 | * 308 | * @param string $format 309 | * @return mixed 310 | */ 311 | public function diff($format = '%i') 312 | { 313 | $now = new \DateTime(); 314 | $date = clone $this->_dateTime; 315 | 316 | return $now->diff($date)->format($format); 317 | } 318 | 319 | /** 320 | * Получение словестного отображения даты 321 | * Например "Сегодня", "Вчера", "Завтра", "14 сентября 2015 г." 322 | * 323 | * @param bool|true $year 324 | * @param bool|false $time 325 | * @return string 326 | */ 327 | public function today($year = true, $time = false) 328 | { 329 | $today = new \DateTime; 330 | $today->setTime(0, 0, 0); 331 | $date = clone $this->_dateTime; 332 | $date->setTime(0, 0, 0); 333 | $result = $this->longDate($year); 334 | if ($today->diff($date)->format('%a') === '0') { 335 | $result = $this->todayStr; 336 | } elseif ($today->diff($date)->format('%R%a') === '+1') { 337 | $result = $this->tomorrowStr; 338 | } elseif ($today->diff($date)->format('%R%a') === '-1') { 339 | $result = $this->yesterdayStr; 340 | } 341 | if ($time) { 342 | $result .= ' ' . $this->shortTime(false); 343 | } 344 | 345 | return $result; 346 | } 347 | 348 | /** 349 | * Получения длинного отображения даты текстом 350 | * Число, месяц, опц. год, опц. время 351 | * 352 | * @param bool|false $year 353 | * @param bool|false $time 354 | * @return string 355 | */ 356 | public function longDate($year = false, $time = false) 357 | { 358 | $result = ''; 359 | $result .= $this->day(); 360 | $result .= ' ' . $this->month(); 361 | if ($year) { 362 | $result .= ' ' . $this->_dateTime->format('Y'); 363 | } 364 | if ($time) { 365 | $result .= ' ' . $this->shortTime(false); 366 | } 367 | 368 | return $result; 369 | } 370 | 371 | /** 372 | * Получения котортого отображения даты 373 | * Опц. день недели, число, 3 буквы месяца 374 | * 375 | * @param bool|false $day 376 | * @return string 377 | */ 378 | public function shortDate($day = false) 379 | { 380 | $result = ''; 381 | if ($day) { 382 | $N = $this->_dateTime->format('N') * 1 - 1; 383 | if (isset($this->shortDay[$N])) { 384 | $result .= $this->shortDay[$N] . ', '; 385 | } 386 | } 387 | $result .= $this->_dateTime->format('j') * 1; 388 | $M = $this->_dateTime->format('n') * 1 - 1; 389 | $result .= ' ' . mb_strtolower($this->shortMonth[$M]); 390 | 391 | return $result; 392 | } 393 | 394 | /** 395 | * Получение короткой записи времени 396 | * Опц. день недели, время 397 | * Например "Пн, 12:01" 398 | * 399 | * @param bool|true $day 400 | * @return string 401 | */ 402 | public function shortTime($day = true) 403 | { 404 | $result = ''; 405 | if ($day) { 406 | $N = $this->_dateTime->format('N') * 1 - 1; 407 | if (isset($this->shortDay[$N])) { 408 | $result .= mb_convert_case($this->shortDay[$N], MB_CASE_TITLE) . ' '; 409 | } 410 | } 411 | $result .= $this->_dateTime->format('H:i'); 412 | 413 | return $result; 414 | } 415 | 416 | /** 417 | * Получение года или интервала годов 418 | * 419 | * @param bool|false $start год начала интервала, если нужен интервал вида "2014 – 2015" 420 | * @return string 421 | */ 422 | public function year($start = false) 423 | { 424 | $result = ''; 425 | if ($start && is_numeric($start) && $start * 1 !== $this->_dateTime->format('Y') * 1) { 426 | $result = $start . ' – '; 427 | } 428 | $result .= $this->_dateTime->format('Y'); 429 | 430 | return $result; 431 | } 432 | 433 | /** 434 | * Получения дней недели в массиве 435 | * 436 | * @return array 437 | */ 438 | public function getWeek() 439 | { 440 | $result = []; 441 | if ($this->_dateTime) { 442 | $this->_dateTime->setTime(0, 0, 0); 443 | $result['currentDate'] = $this->datetime(false); 444 | $result['currentDay'] = $day = (int) $this->_dateTime->format('N'); 445 | for ($i = 1; $i <= 7; $i++) { 446 | $date = clone $this; 447 | $diff = $i - $day; 448 | $result['list'][$i] = $date->modify($diff . " day"); 449 | } 450 | $dateClone = clone $this; 451 | $result['prev'] = (string) $dateClone->modify(-6 - $this->_dateTime->format('N'))->longDate(); 452 | $result['prevDate'] = $dateClone->datetime(false); 453 | $result['prev'] .= ' – ' . (string) $dateClone->modify(6)->longDate(); 454 | $result['current'] = (string) $dateClone->modify(1)->longDate(); 455 | $result['current'] .= ' – ' . (string) $dateClone->modify(6)->longDate(); 456 | $result['next'] = (string) $dateClone->modify(1)->longDate(); 457 | $result['nextDate'] = $dateClone->datetime(false); 458 | $result['next'] .= ' – ' . (string) $dateClone->modify(6)->longDate(); 459 | } 460 | 461 | return $result; 462 | } 463 | 464 | } 465 | --------------------------------------------------------------------------------