|
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 Nette; |
|
12
|
|
|
use Ublaboo\DataGrid\Exception\DataGridDateTimeHelperException; |
|
13
|
|
|
|
|
14
|
|
|
final class DateTimeHelper extends Nette\Object |
|
15
|
|
|
{ |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Try to convert string into DateTime object |
|
19
|
|
|
* @param string $value |
|
20
|
|
|
* @return \DateTime |
|
21
|
|
|
* @throws DataGridDateTimeHelperException |
|
22
|
|
|
*/ |
|
23
|
|
|
public static function tryConvertToDateTime($value) |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* Try to convert string Y-m-d to DateTime object |
|
27
|
|
|
*/ |
|
28
|
|
|
$date = \DateTime::createFromFormat('Y-m-d', $value); |
|
29
|
|
|
|
|
30
|
|
|
if ($date) { |
|
31
|
|
|
return $date; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Try to convert string Y-m-d H:i:s to DateTime object |
|
36
|
|
|
*/ |
|
37
|
|
|
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $value); |
|
38
|
|
|
|
|
39
|
|
|
if ($date) { |
|
40
|
|
|
return $date; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Try to convert string Y-m-d H:i:s.u to DateTime object |
|
45
|
|
|
*/ |
|
46
|
|
|
$date = \DateTime::createFromFormat('Y-m-d H:i:s.u', $value); |
|
47
|
|
|
|
|
48
|
|
|
if ($date) { |
|
49
|
|
|
return $date; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Try strtotime |
|
54
|
|
|
*/ |
|
55
|
|
|
$timestamp = strtotime($value); |
|
56
|
|
|
if (FALSE !== $timestamp) { |
|
57
|
|
|
$date = new \DateTime; |
|
58
|
|
|
$date->setTimestamp($timestamp); |
|
59
|
|
|
|
|
60
|
|
|
return $date; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* Could not convert string to datatime |
|
65
|
|
|
*/ |
|
66
|
|
|
throw new DataGridDateTimeHelperException; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Try to convert string into DateTime object from more date formats |
|
72
|
|
|
* @param string $value |
|
73
|
|
|
* @return \DateTime |
|
74
|
|
|
* @throws DataGridDateTimeHelperException |
|
75
|
|
|
*/ |
|
76
|
|
|
public static function tryConvertToDate($value) |
|
77
|
|
|
{ |
|
78
|
|
|
$formats = ['Y-m-d', 'j. n. Y']; |
|
79
|
|
|
|
|
80
|
|
|
foreach ($formats as $format) { |
|
81
|
|
|
$date = \DateTime::createFromFormat($format, $value); |
|
82
|
|
|
|
|
83
|
|
|
if ($date) { |
|
84
|
|
|
return $date; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
/** |
|
89
|
|
|
* Could not convert string to datatime |
|
90
|
|
|
*/ |
|
91
|
|
|
throw new DataGridDateTimeHelperException; |
|
92
|
|
|
} |
|
93
|
|
|
|
|
94
|
|
|
} |
|
95
|
|
|
|