3 * Creation and parsing of MW-style timestamps.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Tyler Romeo, 2012
26 * Library for creating and parsing MW-style timestamps. Based on the JS
27 * library that does the same thing.
33 * Standard gmdate() formats for the different timestamp types.
35 private static $formats = array(
38 TS_DB
=> 'Y-m-d H:i:s',
39 TS_ISO_8601
=> 'Y-m-d\TH:i:s\Z',
40 TS_ISO_8601_BASIC
=> 'Ymd\THis\Z',
41 TS_EXIF
=> 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
42 TS_RFC2822
=> 'D, d M Y H:i:s',
43 TS_ORACLE
=> 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
44 TS_POSTGRES
=> 'Y-m-d H:i:s',
48 * The actual timestamp being wrapped (DateTime object).
54 * Make a new timestamp and set it to the specified time,
55 * or the current time if unspecified.
59 * @param bool|string $timestamp Timestamp to set, or false for current time
61 public function __construct( $timestamp = false ) {
62 $this->setTimestamp( $timestamp );
66 * Set the timestamp to the specified time, or the current time if unspecified.
68 * Parse the given timestamp into either a DateTime object or a Unix timestamp,
73 * @param string|bool $ts Timestamp to store, or false for now
74 * @throws TimestampException
76 public function setTimestamp( $ts = false ) {
80 // We want to catch 0, '', null... but not date strings starting with a letter.
81 if ( !$ts ||
$ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) {
84 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
86 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
88 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
90 } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
92 $strtime = "@$ts"; // http://php.net/manual/en/datetime.formats.compound.php
93 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
94 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
95 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
96 str_replace( '+00:00', 'UTC', $ts ) );
97 } elseif ( preg_match(
98 '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z?$/',
103 } elseif ( preg_match(
104 '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z?$/',
109 } elseif ( preg_match(
110 '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',
115 } elseif ( preg_match(
116 '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',
121 } elseif ( preg_match(
123 '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' .
125 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' .
127 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S',
130 # TS_RFC2822, accepting a trailing comment.
131 # See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
132 # The regex is a superset of rfc2822 for readability
133 $strtime = strtok( $ts, ';' );
134 } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
137 } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
141 throw new TimestampException( __METHOD__
. ": Invalid timestamp - $ts" );
145 $da = array_map( 'intval', $da );
146 $da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
147 $strtime = call_user_func_array( "sprintf", $da );
151 $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
152 } catch ( Exception
$e ) {
153 throw new TimestampException( __METHOD__
. ': Invalid timestamp format.', $e->getCode(), $e );
156 if ( $final === false ) {
157 throw new TimestampException( __METHOD__
. ': Invalid timestamp format.' );
159 $this->timestamp
= $final;
163 * Get the timestamp represented by this object in a certain form.
165 * Convert the internal timestamp to the specified format and then
170 * @param int $style Constant Output format for timestamp
171 * @throws TimestampException
172 * @return string The formatted timestamp
174 public function getTimestamp( $style = TS_UNIX
) {
175 if ( !isset( self
::$formats[$style] ) ) {
176 throw new TimestampException( __METHOD__
. ': Illegal timestamp output type.' );
179 $output = $this->timestamp
->format( self
::$formats[$style] );
181 if ( ( $style == TS_RFC2822
) ||
( $style == TS_POSTGRES
) ) {
185 if ( $style == TS_MW
&& strlen( $output ) !== 14 ) {
186 throw new TimestampException( __METHOD__
. ': The timestamp cannot be represented in ' .
187 'the specified format' );
194 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
196 * Determine the difference between the timestamp and the current time, and
197 * generate a readable timestamp by returning "<N> <units> ago", where the
198 * largest possible unit is used.
201 * @since 1.22 Uses Language::getHumanTimestamp to produce the timestamp
202 * @deprecated since 1.26 Use Language::getHumanTimestamp directly
204 * @param MWTimestamp|null $relativeTo The base timestamp to compare to (defaults to now)
205 * @param User|null $user User the timestamp is being generated for (or null to use main context's user)
206 * @param Language|null $lang Language to use to make the human timestamp (or null to use main context's language)
207 * @return string Formatted timestamp
209 public function getHumanTimestamp( MWTimestamp
$relativeTo = null, User
$user = null, Language
$lang = null ) {
210 if ( $lang === null ) {
211 $lang = RequestContext
::getMain()->getLanguage();
214 return $lang->getHumanTimestamp( $this, $relativeTo, $user );
218 * Adjust the timestamp depending on the given user's preferences.
222 * @param User $user User to take preferences from
223 * @return DateInterval Offset that was applied to the timestamp
225 public function offsetForUser( User
$user ) {
226 global $wgLocalTZoffset;
228 $option = $user->getOption( 'timecorrection' );
229 $data = explode( '|', $option, 3 );
231 // First handle the case of an actual timezone being specified.
232 if ( $data[0] == 'ZoneInfo' ) {
234 $tz = new DateTimeZone( $data[2] );
235 } catch ( Exception
$e ) {
240 $this->timestamp
->setTimezone( $tz );
241 return new DateInterval( 'P0Y' );
248 // If $option is in fact a pipe-separated value, check the
250 if ( $data[0] == 'System' ) {
251 // First value is System, so use the system offset.
252 if ( $wgLocalTZoffset !== null ) {
253 $diff = $wgLocalTZoffset;
255 } elseif ( $data[0] == 'Offset' ) {
256 // First value is Offset, so use the specified offset
257 $diff = (int)$data[1];
259 // $option actually isn't a pipe separated value, but instead
260 // a comma separated value. Isn't MediaWiki fun?
261 $data = explode( ':', $option );
262 if ( count( $data ) >= 2 ) {
263 // Combination hours and minutes.
264 $diff = abs( (int)$data[0] ) * 60 +
(int)$data[1];
265 if ( (int)$data[0] < 0 ) {
270 $diff = (int)$data[0] * 60;
274 $interval = new DateInterval( 'PT' . abs( $diff ) . 'M' );
276 $interval->invert
= 1;
279 $this->timestamp
->add( $interval );
284 * Generate a purely relative timestamp, i.e., represent the time elapsed between
285 * the given base timestamp and this object.
287 * @param MWTimestamp $relativeTo Relative base timestamp (defaults to now)
288 * @param User $user Use to use offset for
289 * @param Language $lang Language to use
290 * @param array $chosenIntervals Intervals to use to represent it
291 * @return string Relative timestamp
293 public function getRelativeTimestamp(
294 MWTimestamp
$relativeTo = null,
296 Language
$lang = null,
297 array $chosenIntervals = array()
299 if ( $relativeTo === null ) {
300 $relativeTo = new self
;
302 if ( $user === null ) {
303 $user = RequestContext
::getMain()->getUser();
305 if ( $lang === null ) {
306 $lang = RequestContext
::getMain()->getLanguage();
310 $diff = $this->diff( $relativeTo );
312 'GetRelativeTimestamp',
313 array( &$ts, &$diff, $this, $relativeTo, $user, $lang )
315 $seconds = ( ( ( $diff->days
* 24 +
$diff->h
) * 60 +
$diff->i
) * 60 +
$diff->s
);
316 $ts = wfMessage( 'ago', $lang->formatDuration( $seconds, $chosenIntervals ) )
317 ->inLanguage( $lang )->text();
328 public function __toString() {
329 return $this->getTimestamp();
333 * Calculate the difference between two MWTimestamp objects.
336 * @param MWTimestamp $relativeTo Base time to calculate difference from
337 * @return DateInterval|bool The DateInterval object representing the
338 * difference between the two dates or false on failure
340 public function diff( MWTimestamp
$relativeTo ) {
341 return $this->timestamp
->diff( $relativeTo->timestamp
);
345 * Set the timezone of this timestamp to the specified timezone.
348 * @param string $timezone Timezone to set
349 * @throws TimestampException
351 public function setTimezone( $timezone ) {
353 $this->timestamp
->setTimezone( new DateTimeZone( $timezone ) );
354 } catch ( Exception
$e ) {
355 throw new TimestampException( __METHOD__
. ': Invalid timezone.', $e->getCode(), $e );
360 * Get the timezone of this timestamp.
363 * @return DateTimeZone The timezone
365 public function getTimezone() {
366 return $this->timestamp
->getTimezone();
370 * Format the timestamp in a given format.
373 * @param string $format Pattern to format in
374 * @return string The formatted timestamp
376 public function format( $format ) {
377 return $this->timestamp
->format( $format );
381 * Get a timestamp instance in the server local timezone ($wgLocaltimezone)
384 * @param bool|string $ts Timestamp to set, or false for current time
385 * @return MWTimestamp The local instance
387 public static function getLocalInstance( $ts = false ) {
388 global $wgLocaltimezone;
389 $timestamp = new self( $ts );
390 $timestamp->setTimezone( $wgLocaltimezone );
395 * Get a timestamp instance in GMT
398 * @param bool|string $ts Timestamp to set, or false for current time
399 * @return MWTimestamp The instance
401 public static function getInstance( $ts = false ) {
402 return new self( $ts );