1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @copyright Copyright (c) 2015 ublaboo <[email protected]> |
5
|
|
|
* @author Pavel Janda <[email protected]> |
6
|
|
|
* @package Ublaboo |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Ublaboo\DataGrid\Utils; |
10
|
|
|
|
11
|
|
|
use Ublaboo\DataGrid\Exception\DataGridDateTimeHelperException; |
12
|
|
|
|
13
|
|
|
final class DateTimeHelper extends \Nette\Object |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Try to convert string into DateTime object |
18
|
|
|
* @param mixed $value |
19
|
|
|
* @param string[] $formats |
20
|
|
|
* @return \DateTime |
21
|
|
|
* @throws DataGridDateTimeHelperException |
22
|
|
|
*/ |
23
|
|
|
public static function tryConvertToDateTime($value, array $formats = []) |
24
|
|
|
{ |
25
|
|
|
return static::fromString($value, $formats); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Try to convert string into DateTime object from more date formats |
31
|
|
|
* @param mixed $value |
32
|
|
|
* @param string[] $formats |
33
|
|
|
* @return \DateTime |
34
|
|
|
* @throws DataGridDateTimeHelperException |
35
|
|
|
*/ |
36
|
|
|
public static function tryConvertToDate($value, array $formats = []) |
37
|
|
|
{ |
38
|
|
|
return static::fromString($value, $formats); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Convert string into DateTime object from more date without time |
44
|
|
|
* @param mixed $value |
45
|
|
|
* @param string[] $formats |
46
|
|
|
* @return \DateTime |
47
|
|
|
* @throws DataGridDateTimeHelperException |
48
|
|
|
*/ |
49
|
|
|
public static function fromString($value, array $formats = []) |
50
|
|
|
{ |
51
|
|
|
$formats = array_merge($formats, [ |
52
|
|
|
'Y-m-d H:i:s.u', |
53
|
|
|
'Y-m-d H:i:s', |
54
|
|
|
'Y-m-d', |
55
|
|
|
'j. n. Y G:i:s', |
56
|
|
|
'j. n. Y G:i', |
57
|
|
|
'j. n. Y', |
58
|
|
|
]); |
59
|
|
|
|
60
|
|
|
if ($value instanceof \DateTime) { |
61
|
|
|
return $value; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
foreach ($formats as $format) { |
65
|
|
|
if (!is_string($format) || !$date = \DateTime::createFromFormat($format, $value)) { |
66
|
|
|
continue; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $date; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$timestamp = strtotime($value); |
73
|
|
|
|
74
|
|
|
if ($timestamp !== FALSE) { |
75
|
|
|
$date = new \DateTime; |
76
|
|
|
$date->setTimestamp($timestamp); |
77
|
|
|
|
78
|
|
|
return $date; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
throw new DataGridDateTimeHelperException; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
} |
85
|
|
|
|