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 = [
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|int|float $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 ) {
81 // We want to catch 0, '', null... but not date strings starting with a letter.
82 if ( !$ts ||
$ts === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) {
85 } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
87 } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
89 } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
91 } elseif ( preg_match( '/^(-?\d{1,13})(\.\d+)?$/D', $ts, $m ) ) {
93 $strtime = "@{$m[1]}"; // http://php.net/manual/en/datetime.formats.compound.php
94 } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
95 # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
96 $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
97 str_replace( '+00:00', 'UTC', $ts ) );
98 } elseif ( preg_match(
99 '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z?$/',
104 } elseif ( preg_match(
105 '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z?$/',
110 } elseif ( preg_match(
111 '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',
116 } elseif ( preg_match(
117 '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',
122 } elseif ( preg_match(
124 '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' .
126 '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' .
128 '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S',
131 # TS_RFC2822, accepting a trailing comment.
132 # See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
133 # The regex is a superset of rfc2822 for readability
134 $strtime = strtok( $ts, ';' );
135 } 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 ) ) {
138 } 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 ) ) {
142 throw new TimestampException( __METHOD__
. ": Invalid timestamp - $ts" );
146 $da = array_map( 'intval', $da );
147 $da[0] = "%04d-%02d-%02dT%02d:%02d:%02d.00+00:00";
148 $strtime = call_user_func_array( "sprintf", $da );
152 $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
153 } catch ( Exception
$e ) {
154 throw new TimestampException( __METHOD__
. ': Invalid timestamp format.', $e->getCode(), $e );
157 if ( $final === false ) {
158 throw new TimestampException( __METHOD__
. ': Invalid timestamp format.' );
160 $this->timestamp
= $final;
164 * Get the timestamp represented by this object in a certain form.
166 * Convert the internal timestamp to the specified format and then
171 * @param int $style Constant Output format for timestamp
172 * @throws TimestampException
173 * @return string The formatted timestamp
175 public function getTimestamp( $style = TS_UNIX
) {
176 if ( !isset( self
::$formats[$style] ) ) {
177 throw new TimestampException( __METHOD__
. ': Illegal timestamp output type.' );
180 $output = $this->timestamp
->format( self
::$formats[$style] );
182 if ( ( $style == TS_RFC2822
) ||
( $style == TS_POSTGRES
) ) {
186 if ( $style == TS_MW
&& strlen( $output ) !== 14 ) {
187 throw new TimestampException( __METHOD__
. ': The timestamp cannot be represented in ' .
188 'the specified format' );
195 * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
197 * Determine the difference between the timestamp and the current time, and
198 * generate a readable timestamp by returning "<N> <units> ago", where the
199 * largest possible unit is used.
202 * @since 1.22 Uses Language::getHumanTimestamp to produce the timestamp
203 * @deprecated since 1.26 Use Language::getHumanTimestamp directly
205 * @param MWTimestamp|null $relativeTo The base timestamp to compare to (defaults to now)
206 * @param User|null $user User the timestamp is being generated for
207 * (or null to use main context's user)
208 * @param Language|null $lang Language to use to make the human timestamp
209 * (or null to use main context's language)
210 * @return string Formatted timestamp
212 public function getHumanTimestamp(
213 MWTimestamp
$relativeTo = null, User
$user = null, Language
$lang = null
215 if ( $lang === null ) {
216 $lang = RequestContext
::getMain()->getLanguage();
219 return $lang->getHumanTimestamp( $this, $relativeTo, $user );
223 * Adjust the timestamp depending on the given user's preferences.
227 * @param User $user User to take preferences from
228 * @return DateInterval Offset that was applied to the timestamp
230 public function offsetForUser( User
$user ) {
231 global $wgLocalTZoffset;
233 $option = $user->getOption( 'timecorrection' );
234 $data = explode( '|', $option, 3 );
236 // First handle the case of an actual timezone being specified.
237 if ( $data[0] == 'ZoneInfo' ) {
239 $tz = new DateTimeZone( $data[2] );
240 } catch ( Exception
$e ) {
245 $this->timestamp
->setTimezone( $tz );
246 return new DateInterval( 'P0Y' );
253 // If $option is in fact a pipe-separated value, check the
255 if ( $data[0] == 'System' ) {
256 // First value is System, so use the system offset.
257 if ( $wgLocalTZoffset !== null ) {
258 $diff = $wgLocalTZoffset;
260 } elseif ( $data[0] == 'Offset' ) {
261 // First value is Offset, so use the specified offset
262 $diff = (int)$data[1];
264 // $option actually isn't a pipe separated value, but instead
265 // a comma separated value. Isn't MediaWiki fun?
266 $data = explode( ':', $option );
267 if ( count( $data ) >= 2 ) {
268 // Combination hours and minutes.
269 $diff = abs( (int)$data[0] ) * 60 +
(int)$data[1];
270 if ( (int)$data[0] < 0 ) {
275 $diff = (int)$data[0] * 60;
279 $interval = new DateInterval( 'PT' . abs( $diff ) . 'M' );
281 $interval->invert
= 1;
284 $this->timestamp
->add( $interval );
289 * Generate a purely relative timestamp, i.e., represent the time elapsed between
290 * the given base timestamp and this object.
292 * @param MWTimestamp $relativeTo Relative base timestamp (defaults to now)
293 * @param User $user Use to use offset for
294 * @param Language $lang Language to use
295 * @param array $chosenIntervals Intervals to use to represent it
296 * @return string Relative timestamp
298 public function getRelativeTimestamp(
299 MWTimestamp
$relativeTo = null,
301 Language
$lang = null,
302 array $chosenIntervals = []
304 if ( $relativeTo === null ) {
305 $relativeTo = new self
;
307 if ( $user === null ) {
308 $user = RequestContext
::getMain()->getUser();
310 if ( $lang === null ) {
311 $lang = RequestContext
::getMain()->getLanguage();
315 $diff = $this->diff( $relativeTo );
317 'GetRelativeTimestamp',
318 [ &$ts, &$diff, $this, $relativeTo, $user, $lang ]
320 $seconds = ( ( ( $diff->days
* 24 +
$diff->h
) * 60 +
$diff->i
) * 60 +
$diff->s
);
321 $ts = wfMessage( 'ago', $lang->formatDuration( $seconds, $chosenIntervals ) )
322 ->inLanguage( $lang )->text();
333 public function __toString() {
334 return $this->getTimestamp();
338 * Calculate the difference between two MWTimestamp objects.
341 * @param MWTimestamp $relativeTo Base time to calculate difference from
342 * @return DateInterval|bool The DateInterval object representing the
343 * difference between the two dates or false on failure
345 public function diff( MWTimestamp
$relativeTo ) {
346 return $this->timestamp
->diff( $relativeTo->timestamp
);
350 * Set the timezone of this timestamp to the specified timezone.
353 * @param string $timezone Timezone to set
354 * @throws TimestampException
356 public function setTimezone( $timezone ) {
358 $this->timestamp
->setTimezone( new DateTimeZone( $timezone ) );
359 } catch ( Exception
$e ) {
360 throw new TimestampException( __METHOD__
. ': Invalid timezone.', $e->getCode(), $e );
365 * Get the timezone of this timestamp.
368 * @return DateTimeZone The timezone
370 public function getTimezone() {
371 return $this->timestamp
->getTimezone();
375 * Get the localized timezone message, if available.
377 * Premade translations are not shipped as format() may return whatever the
378 * system uses, localized or not, so translation must be done through wiki.
381 * @return Message The localized timezone message
383 public function getTimezoneMessage() {
384 $tzMsg = $this->format( 'T' ); // might vary on DST changeover!
385 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
386 $msg = wfMessage( $key );
387 if ( $msg->exists() ) {
390 return new RawMessage( $tzMsg );
395 * Format the timestamp in a given format.
398 * @param string $format Pattern to format in
399 * @return string The formatted timestamp
401 public function format( $format ) {
402 return $this->timestamp
->format( $format );
406 * Get a timestamp instance in the server local timezone ($wgLocaltimezone)
409 * @param bool|string $ts Timestamp to set, or false for current time
410 * @return MWTimestamp The local instance
412 public static function getLocalInstance( $ts = false ) {
413 global $wgLocaltimezone;
414 $timestamp = new self( $ts );
415 $timestamp->setTimezone( $wgLocaltimezone );
420 * Get a timestamp instance in GMT
423 * @param bool|string $ts Timestamp to set, or false for current time
424 * @return MWTimestamp The instance
426 public static function getInstance( $ts = false ) {
427 return new self( $ts );