Skip to content

Commit e1163b1

Browse files
committed
Merge pull request #709 from CrAzE124/master
Added Util::convertDateTimeObject to support converting \DateTime object...
2 parents 0d2400b + ec910f5 commit e1163b1

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

changes.txt

+3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
CHANGES
22

3+
2014-10-22
4+
- Added Util::convertDateTimeObject to Util class to easily convert \DateTime objects to required format #708
5+
36
2014-10-10
47
- Fixed Response::isOk() to work better with bulk update api
58

lib/Elastica/Util.php

+17
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,23 @@ public static function convertDate($date)
119119
return $string;
120120
}
121121

122+
/**
123+
* Convert a \DateTime object to format: 1995-12-31T23:59:59Z+02:00
124+
*
125+
* Converts it to the lucene format, including the appropriate TimeZone
126+
*
127+
* @param \DateTime $dateTime
128+
* @param boolean $includeTimezone
129+
* @return string
130+
*/
131+
public static function convertDateTimeObject(\DateTime $dateTime, $includeTimezone = true)
132+
{
133+
$formatString = 'Y-m-d\TH:i:s' . ($includeTimezone === true ? 'P' : '\Z');
134+
$string = $dateTime->format($formatString);
135+
136+
return $string;
137+
}
138+
122139
/**
123140
* Tries to guess the name of the param, based on its class
124141
* Example: \Elastica\Filter\HasChildFilter => has_child

test/lib/Elastica/Test/UtilTest.php

+24
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,28 @@ public function testConvertRequestToCurlCommand()
7474
$this->assertEquals($expected, $curlCommand);
7575

7676
}
77+
78+
public function testConvertDateTimeObjectWithTimezone()
79+
{
80+
$dateTimeObject = new \DateTime();
81+
$timestamp = $dateTimeObject->getTimestamp();
82+
83+
$convertedString = Util::convertDateTimeObject($dateTimeObject);
84+
85+
$date = date('Y-m-d\TH:i:sP', $timestamp);
86+
87+
$this->assertEquals($convertedString, $date);
88+
}
89+
90+
public function testConvertDateTimeObjectWithoutTimezone()
91+
{
92+
$dateTimeObject = new \DateTime();
93+
$timestamp = $dateTimeObject->getTimestamp();
94+
95+
$convertedString = Util::convertDateTimeObject($dateTimeObject, false);
96+
97+
$date = date('Y-m-d\TH:i:s\Z', $timestamp);
98+
99+
$this->assertEquals($convertedString, $date);
100+
}
77101
}

0 commit comments

Comments
 (0)