Completed
Push — master ( abb118...88c170 )
by Pavel
02:22
created

DateTimeHelper   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 1
dl 0
loc 79
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A tryConvertToDateTime() 0 4 1
A tryConvertToDate() 0 4 1
C fromString() 0 41 7
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
		if ($value instanceof \DateTimeImmutable) {
65
			$date = new \DateTime('now', $value->getTimezone());
66
			$date->setTimestamp($value->getTimestamp());
67
68
			return $date;
69
		}
70
71
		foreach ($formats as $format) {
72
			if (!is_string($format) || !$date = \DateTime::createFromFormat($format, $value)) {
73
				continue;
74
			}
75
76
			return $date;
77
		}
78
79
		$timestamp = strtotime($value);
80
81
		if ($timestamp !== FALSE) {
82
			$date = new \DateTime;
83
			$date->setTimestamp($timestamp);
84
85
			return $date;
86
		}
87
88
		throw new DataGridDateTimeHelperException;
89
	}
90
91
}
92