Added new MWTimestamp::getRelativeTimestamp for pure relative.
[lhc/web/wiklou.git] / includes / Timestamp.php
index 92e914e..9952001 100644 (file)
@@ -125,7 +125,7 @@ class MWTimestamp {
 
                try {
                        $final = new DateTime( $strtime, new DateTimeZone( 'GMT' ) );
-               } catch( Exception $e ) {
+               } catch ( Exception $e ) {
                        throw new TimestampException( __METHOD__ . ' Invalid timestamp format.' );
                }
 
@@ -261,7 +261,7 @@ class MWTimestamp {
                        }
                }
 
-               $interval = new DateInterval('PT' . abs( $diff ) . 'M');
+               $interval = new DateInterval( 'PT' . abs( $diff ) . 'M' );
                if ( $diff < 1 ) {
                        $interval->invert = 1;
                }
@@ -270,6 +270,44 @@ class MWTimestamp {
                return $interval;
        }
 
+       /**
+        * Generate a purely relative timestamp, i.e., represent the time elapsed between
+        * the given base timestamp and this object.
+        *
+        * @param MWTimestamp $relativeTo Relative base timestamp (defaults to now)
+        * @param User $user Use to use offset for
+        * @param Language $lang Language to use
+        * @param array $chosenIntervals Intervals to use to represent it
+        * @return string Relative timestamp
+        */
+       public function getRelativeTimestamp(
+               MWTimestamp $relativeTo = null,
+               User $user = null,
+               Language $lang = null,
+               array $chosenIntervals = array()
+       ) {
+               if ( $relativeTo === null ) {
+                       $relativeTo = new self;
+               }
+               if ( $user === null ) {
+                       $user = RequestContext::getMain()->getUser();
+               }
+               if ( $lang === null ) {
+                       $lang = RequestContext::getMain()->getLanguage();
+               }
+
+               $ts = '';
+               $diff = $this->diff( $relativeTo );
+               if ( wfRunHooks( 'GetRelativeTimestamp', array( &$ts, &$diff, $this, $relativeTo, $user, $lang ) ) ) {
+                       $seconds = ( ( ( $diff->days * 24 + $diff->h ) * 60 + $diff->i ) * 60 + $diff->s );
+                       $ts = wfMessage( 'ago', $lang->formatDuration( $seconds, $chosenIntervals ) )
+                               ->inLanguage( $lang )
+                               ->text();
+               }
+
+               return $ts;
+       }
+
        /**
         * @since 1.20
         *