Completed
Push — master ( a6f36a...985feb )
by Pavel
02:40
created

DateTimeHelper::tryConvertToDateTime()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 45
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 45
rs 8.439
cc 5
eloc 16
nc 5
nop 1
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