Пример #1
0
 public function testDateOffset()
 {
     $date = new Date('2015-04-25+01:00');
     $this->assertEquals(2015, $date->getYear());
     $this->assertEquals(4, $date->getMonth());
     $this->assertEquals(25, $date->getDay());
     $this->assertEquals(3600, $date->getOffset());
     $this->assertInstanceOf('DateTimeZone', $date->getTimeZone());
     $this->assertEquals('2015-04-25+01:00', $date->toString());
 }
Пример #2
0
  function testSetByLocaleStringShort()
  {
    $date = new Date();

    $locale = new Locale('en');
    $date->setByLocaleString($locale, 'Thu 20 Jan 2005', '%a %d %b %Y');

    $this->assertEqual($date->getMonth(), 1);
    $this->assertEqual($date->getYear(), 2005);
    $this->assertEqual($date->getDay(), 20);
  }
 public static function getAgeByBirthDate(Date $birthDate, $actualDate = null)
 {
     if ($actualDate) {
         Assert::isInstance($actualDate, 'Date');
     } else {
         $actualDate = Date::makeToday();
     }
     $result = $actualDate->getYear() - $birthDate->getYear();
     if ($actualDate->getMonth() < $birthDate->getMonth() || $actualDate->getMonth() == $birthDate->getMonth() && $actualDate->getDay() < $birthDate->getDay()) {
         // - Happy birthday?
         // - Happy go to hell. Not yet in this year.
         --$result;
     }
     return $result;
 }
Пример #4
0
 public function isEquals(Date $date)
 {
     return $this->year === $date->getYear() && $this->month === $date->getMonth() && $this->day === $date->getDay();
 }
Пример #5
0
 /**
  * Returns an array of conversions.
  *
  * @param array $aParams
  * @return array
  */
 function getConversions($aParams)
 {
     $conf = $GLOBALS['_MAX']['CONF'];
     $oDbh =& OA_DB::singleton();
     $where = '';
     if (!empty($aParams['day'])) {
         $aParams['day_begin'] = $aParams['day_end'] = $aParams['day'];
     }
     if (!empty($aParams['day_begin'])) {
         $oStart = new Date($aParams['day_begin']);
         $oStart->setHour(0);
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oStart->toUTC();
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['day_end'])) {
         $oEnd = new Date($aParams['day_end']);
         $oEnd->setHour(23);
         $oEnd->setMinute(59);
         $oEnd->setSecond(59);
         $oEnd->toUTC();
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['month'])) {
         $oStart = new Date("{$aParams['month']}-01");
         $oStart->setHour(0);
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oEnd = new Date(Date_Calc::beginOfNextMonth($oStart->getDay(), $oStart->getMonth, $oStart->getYear(), '%Y-%m-%d'));
         $oEnd->setHour(0);
         $oEnd->setMinute(0);
         $oEnd->setSecond(0);
         $oEnd->subtractSeconds(1);
         $oStart->toUTC();
         $oEnd->toUTC();
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['day_hour'])) {
         $oStart = new Date("{$aParams['day_hour']}:00:00");
         $oStart->setMinute(0);
         $oStart->setSecond(0);
         $oEnd = new Date($oStart);
         $oStart->setMinute(59);
         $oStart->setSecond(59);
         $where .= ' AND ac.tracker_date_time >= ' . $oDbh->quote($oStart->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
         $where .= ' AND ac.tracker_date_time <= ' . $oDbh->quote($oEnd->format('%Y-%m-%d %H:%M:%S'), 'timestamp');
     }
     if (!empty($aParams['agency_id'])) {
         $where .= ' AND c.agencyid=' . $oDbh->quote($aParams['agency_id'], 'integer');
     }
     if (!empty($aParams['clientid'])) {
         $where .= ' AND c.clientid=' . $oDbh->quote($aParams['clientid'], 'integer');
     }
     if (isset($aParams['zonesIds'])) {
         $where .= ' AND ac.zone_id IN (' . $oDbh->escape(implode(',', $aParams['zonesIds'])) . ")";
     }
     if (!empty($aParams['campaignid'])) {
         $where .= ' AND m.campaignid=' . $oDbh->quote($aParams['campaignid'], 'integer');
     }
     if (!empty($aParams['bannerid'])) {
         $where .= ' AND d.bannerid=' . $oDbh->quote($aParams['bannerid'], 'integer');
     }
     if (!empty($aParams['statuses'])) {
         $where .= ' AND ac.connection_status IN (' . $oDbh->escape(implode(',', $aParams['statuses'])) . ')';
     }
     if (isset($aParams['startRecord']) && is_numeric($aParams['startRecord']) && is_numeric($aParams['perPage'])) {
         $limit = ' LIMIT ' . $oDbh->quote($aParams['perPage'], 'text', false) . ' OFFSET ' . $oDbh->quote($aParams['startRecord'], 'text', false);
     } elseif (!empty($aParams['perPage'])) {
         $limit = ' LIMIT ' . $oDbh->quote($aParams['perPage'], 'integer', false) . ' OFFSET 0';
     } else {
         $limit = '';
     }
     $query = "SELECT\n            ac.data_intermediate_ad_connection_id as connection_id,\n            c.clientid,\n            m.campaignid,\n            m.campaignname AS campaignname,\n            ac.tracker_id as tracker_id,\n            ac.connection_status,\n            ac.connection_date_time AS connection_date_time,\n            ac.tracker_date_time as date_time,\n            t.trackername,\n            ac.tracker_ip_address,\n            ac.tracker_country,\n            ac.connection_action,\n            t.type AS connection_type,\n            ac.tracker_country,\n            ac.ad_id,\n            ac.creative_id,\n            ac.zone_id,\n            ac.comments\n        FROM\n            {$conf['table']['prefix']}{$conf['table']['clients']} AS c,\n            {$conf['table']['prefix']}{$conf['table']['data_intermediate_ad_connection']} AS ac,\n            {$conf['table']['prefix']}{$conf['table']['banners']} AS d,\n            {$conf['table']['prefix']}{$conf['table']['campaigns']} AS m,\n            {$conf['table']['prefix']}{$conf['table']['trackers']} AS t\n        WHERE\n            c.clientid=m.clientid\n            AND m.campaignid=d.campaignid\n            AND d.bannerid=ac.ad_id\n            AND t.trackerid=ac.tracker_id\n            AND ac.inside_window = 1\n            " . $where . "\n        ORDER BY\n            ac.tracker_date_time\n        {$limit}";
     $aStats = $oDbh->queryAll($query, null, MDB2_FETCHMODE_DEFAULT, true);
     $oNow = new Date();
     foreach (array_keys($aStats) as $k) {
         $oDate = new Date($aStats[$k]['date_time']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aStats[$k]['date_time'] = $oDate->format('%Y-%m-%d %H:%M:%S');
         $oDate = new Date($aStats[$k]['connection_date_time']);
         $oDate->setTZbyID('UTC');
         $oDate->convertTZ($oNow->tz);
         $aStats[$k]['connection_date_time'] = $oDate->format('%Y-%m-%d %H:%M:%S');
     }
     return $aStats;
 }
Пример #6
0
function transferFormerFinishedTransactions($account)
{
    global $us;
    if ($us->getProperty('autoExpandPlannedTransactions') == false) {
        return;
    }
    $now = new Date();
    $now->setHour(0);
    $now->setMinute(0);
    $now->setSecond(0);
    $account->setType('planned');
    $account->setFilter(array(array('key' => 'beginDate', 'op' => 'le', 'val' => $now)));
    try {
        $lastInsertDate = $us->getProperty('Account_' . $account->getId() . '_LastTransferFormerFinishedTransactions');
    } catch (BadgerException $ex) {
        $lastInsertDate = new Date('1000-01-01');
    }
    $us->setProperty('Account_' . $account->getId() . '_LastTransferFormerFinishedTransactions', $now);
    if (!$lastInsertDate->before($now)) {
        return;
    }
    while ($currentTransaction = $account->getNextPlannedTransaction()) {
        $date = new Date($currentTransaction->getBeginDate());
        $dayOfMonth = $date->getDay();
        //While we are before now and the end date of this transaction
        while (!$date->after($now) && !$date->after(is_null($tmp = $currentTransaction->getEndDate()) ? new Date('9999-12-31') : $tmp)) {
            if ($date->after($lastInsertDate)) {
                $account->addFinishedTransaction($currentTransaction->getAmount(), $currentTransaction->getTitle(), $currentTransaction->getDescription(), new Date($date), $currentTransaction->getTransactionPartner(), $currentTransaction->getCategory(), $currentTransaction->getOutsideCapital(), false, true);
            }
            //do the date calculation
            switch ($currentTransaction->getRepeatUnit()) {
                case 'day':
                    $date->addSeconds($currentTransaction->getRepeatFrequency() * 24 * 60 * 60);
                    break;
                case 'week':
                    $date->addSeconds($currentTransaction->getRepeatFrequency() * 7 * 24 * 60 * 60);
                    break;
                case 'month':
                    //Set the month
                    $date = new Date(Date_Calc::endOfMonthBySpan($currentTransaction->getRepeatFrequency(), $date->getMonth(), $date->getYear(), '%Y-%m-%d'));
                    //And count back as far as the last valid day of this month
                    while ($date->getDay() > $dayOfMonth) {
                        $date->subtractSeconds(24 * 60 * 60);
                    }
                    break;
                case 'year':
                    $newYear = $date->getYear() + $currentTransaction->getRepeatFrequency();
                    if ($dayOfMonth == 29 && $date->getMonth() == 2 && !Date_Calc::isLeapYear($newYear)) {
                        $date->setDay(28);
                    } else {
                        $date->setDay($dayOfMonth);
                    }
                    $date->setYear($newYear);
                    break;
                default:
                    throw new BadgerException('Account', 'IllegalRepeatUnit', $currentTransaction->getRepeatUnit());
                    exit;
            }
        }
    }
}
Пример #7
0
 /**
  * Formats a 
  *
  * @param   util.Date d
  * @return  string
  */
 public function format(Date $d)
 {
     $out = '';
     foreach ($this->format as $token) {
         switch ($token) {
             case '%Y':
                 $out .= $d->getYear();
                 break;
             case '%m':
                 $out .= str_pad($d->getMonth(), 2, '0', STR_PAD_LEFT);
                 break;
             case '%d':
                 $out .= str_pad($d->getDay(), 2, '0', STR_PAD_LEFT);
                 break;
             case '%H':
                 $out .= str_pad($d->getHours(), 2, '0', STR_PAD_LEFT);
                 break;
             case '%M':
                 $out .= str_pad($d->getMinutes(), 2, '0', STR_PAD_LEFT);
                 break;
             case '%S':
                 $out .= str_pad($d->getSeconds(), 2, '0', STR_PAD_LEFT);
                 break;
             case '%p':
                 $h = $d->getHours();
                 $out .= $h >= 12 ? 'PM' : 'AM';
                 break;
             case '%I':
                 $out .= str_pad($d->getHours() % 12, 2, '0', STR_PAD_LEFT);
                 break;
             case '%z':
                 $out .= $d->getTimeZone()->getName();
                 break;
             case '%Z':
                 $out .= $d->getOffset();
                 break;
             case is_array($token):
                 $out .= $token[1][call_user_func(array($d, 'get' . $token[0])) - 1];
                 break;
             default:
                 $out .= $token;
         }
     }
     return $out;
 }
Пример #8
0
 /**
  * DB_DataObject_FormBuilder::_date2array()
  *
  * Takes a string representing a date or a unix timestamp and turns it into an
  * array suitable for use with the QuickForm data element.
  * When using a string, make sure the format can be handled by the PEAR::Date constructor!
  *
  * Beware: For the date conversion to work, you must at least use the letters "d", "m" and "Y" in
  * your format string (see "dateElementFormat" option). If you want to enter a time as well,
  * you will have to use "H", "i" and "s" as well. Other letters will not work! Exception: You can
  * also use "M" instead of "m" if you want plain text month names.
  *
  * @param mixed $date   A unix timestamp or the string representation of a date, compatible to strtotime()
  * @return array
  * @access protected
  */
 function _date2array($date)
 {
     $da = array();
     if (is_string($date)) {
         // Get PEAR::Date class definition, if needed
         include_once 'Date.php';
         $dObj = new Date($date);
         $da['d'] = $dObj->getDay();
         $da['l'] = $da['D'] = $dObj->getDayOfWeek();
         $da['m'] = $da['M'] = $da['F'] = $dObj->getMonth();
         $da['Y'] = $da['y'] = $dObj->getYear();
         $da['H'] = $dObj->getHour();
         $da['h'] = $da['H'] % 12;
         if ($da['h'] == 0) {
             $da['h'] = 12;
         }
         $da['i'] = $dObj->getMinute();
         $da['s'] = $dObj->getSecond();
         if ($da['H'] >= 12) {
             $da['a'] = 'pm';
             $da['A'] = 'PM';
         } else {
             $da['a'] = 'am';
             $da['A'] = 'AM';
         }
         unset($dObj);
     } else {
         if (is_int($date)) {
             $time = $date;
         } else {
             $time = time();
         }
         $da['d'] = date('d', $time);
         $da['l'] = $da['D'] = date('w', $time);
         $da['m'] = $da['M'] = $da['F'] = date('m', $time);
         $da['Y'] = $da['y'] = date('Y', $time);
         $da['H'] = date('H', $time);
         $da['h'] = date('h', $time);
         $da['i'] = date('i', $time);
         $da['s'] = date('s', $time);
         $da['a'] = date('a', $time);
         $da['A'] = date('A', $time);
     }
     $this->debug('<i>_date2array():</i> from ' . $date . ' ...');
     return $da;
 }
 /**
  * Checks if the given day is the current day
  *
  * @param mixed $stamp Any timestamp format recognized by Pear::Date
  *
  * @return boolean
  * @access protected
  */
 function isToday($stamp)
 {
     static $today = null;
     if (is_null($today)) {
         $today = new Date();
     }
     $date = Calendar_Engine_PearDate::stampCollection($stamp);
     return $date->day == $today->getDay() && $date->month == $today->getMonth() && $date->year == $today->getYear();
 }
 private function computeSubscriptionDays($p_publication, $p_subscriptionTime) {
     $startDate = new Date();
     if ($p_publication->getTimeUnit() == 'D') {
         return $p_subscriptionTime;
     } elseif ($p_publication->getTimeUnit() == 'W') {
         return 7 * $p_subscriptionTime;
     } elseif ($p_publication->getTimeUnit() == 'M') {
         $endDate = new Date();
         $months = $p_subscriptionTime + $endDate->getMonth();
         $years = (int)($months / 12);
         $months = $months % 12;
         $endDate->setYear($endDate->getYear() + $years);
         $endDate->setMonth($months);
     } elseif ($p_publication->getTimeUnit() == 'Y') {
         $endDate = new Date();
         $endDate->setYear($endDate->getYear() + $p_subscriptionTime);
     }
     $dateCalc = new Date_Calc();
     return $dateCalc->dateDiff($endDate->getDay(), $endDate->getMonth(),
     $endDate->getYear(), $startDate->getDay(), $startDate->getMonth(), $startDate->getYear());
 }
Пример #11
0
 /**
  * @covers Geissler\Converter\Model\Date::getDay
  */
 public function testGetDay()
 {
     $this->assertInstanceOf($this->class, $this->object->setDay(19));
     $this->assertEquals(19, $this->object->getDay());
 }
 /**
  * Returns a date in the format used by MS-DOS.
  *
  * @see     http://www.vsft.com/hal/dostime.htm
  * @param   util.Date date
  * @return  int
  */
 protected function dosDate(Date $date)
 {
     return (($date->getYear() - 1980 & 0x7f) << 4 | $date->getMonth() & 0xf) << 5 | $date->getDay() & 0x1f;
 }
Пример #13
0
 /**
  * Actualiza los datos de la tarea duplicada.
  * @version 26-02-09
  * @author Ana Martín
  */
 protected function updateDuplicarTareaFromRequest()
 {
     $tarea = $this->getRequestParameter('tarea');
     $value = sfContext::getInstance()->getI18N()->getTimestampForCulture($tarea['fecha_inicio']['date'], $this->getUser()->getCulture());
     $mi_date = new Date($value);
     $mi_date->setHours(isset($tarea['fecha_inicio']['hour']) ? $tarea['fecha_inicio']['hour'] : 0);
     $mi_date->setMinutes(isset($tarea['fecha_inicio']['minute']) ? $tarea['fecha_inicio']['minute'] : 0);
     $this->nueva_tarea->setFechaInicio($mi_date->getTimestamp());
     if (isset($tarea['fecha_vencimiento'])) {
         $value = sfContext::getInstance()->getI18N()->getTimestampForCulture($tarea['fecha_vencimiento']['date'], $this->getUser()->getCulture());
         $mi_date = new Date($value);
         $mi_date->setHours(isset($tarea['fecha_vencimiento']['hour']) ? $tarea['fecha_vencimiento']['hour'] : 0);
         $mi_date->setMinutes(isset($tarea['fecha_vencimiento']['minute']) ? $tarea['fecha_vencimiento']['minute'] : 0);
         $this->nueva_tarea->setFechaVencimiento($mi_date->getTimestamp());
     } else {
         if (isset($tarea['duracion'])) {
             $duracion_minutos = $tarea['duracion'];
             $fecha_vencimiento = mktime($mi_date->getHours(), $mi_date->getMinutes() + $duracion_minutos, 0, $mi_date->getMonth(), $mi_date->getDay(), $mi_date->getYear());
             $this->nueva_tarea->setFechaVencimiento(date('Y-m-d H:i', $fecha_vencimiento));
         } else {
             $this->nueva_tarea->setFechaVencimiento($mi_date->getTimestamp());
         }
     }
     if (isset($tarea['id_usuario'])) {
         $this->nueva_tarea->setIdUsuario($tarea['id_usuario']);
     }
 }
Пример #14
0
function getTemplateArrayCalendar($o_minDay, $s_date, $period)
{
    // today
    $today = new Date(getDateFromTimestamp(time()));
    $tsToday = $today->getTimestamp();
    // date asked for statistics
    $dateAsked = new Date($s_date);
    // used for going througt the month
    $date = new Date($s_date);
    $month = $date->getMonth();
    $year = $date->getYear();
    $prefixDay = $year . "-" . $month . "-";
    $date->setDate($prefixDay . '01');
    $week = $date->getWeek();
    $day = 1;
    $ts = $date->getTimestamp();
    while ($date->getMonth() == $month) {
        // day exists in stats, isn't it too old or in the future ?
        if ($date->getTimestamp() >= $o_minDay->getTimestamp() && $date->getTimestamp() <= $tsToday) {
            $exists = 1;
        } else {
            $exists = 0;
        }
        // day selected for stats view ?
        if ($period == DB_ARCHIVES_PERIOD_DAY && $date->getDay() == $dateAsked->getDay() || $period == DB_ARCHIVES_PERIOD_WEEK && $date->getWeek() == $dateAsked->getWeek() || $period == DB_ARCHIVES_PERIOD_MONTH || $period == DB_ARCHIVES_PERIOD_YEAR) {
            $selected = 1;
        } else {
            $selected = 0;
        }
        $weekNo = $date->getWeek() - $week;
        if (defined('MONDAY_FIRST') && MONDAY_FIRST == 'no' && date("w", $ts) == 0) {
            $weekNo += 1;
        }
        $dayOfWeek = (int) (!defined('MONDAY_FIRST') || MONDAY_FIRST == 'yes' ? date("w", $ts) == 0 ? 6 : date("w", $ts) - 1 : date("w", $ts));
        $return[$weekNo][$dayOfWeek] = array('day' => substr($date->getDay(), 0, 1) === '0' ? substr($date->getDay(), 1, 2) : $date->getDay(), 'date' => $date->get(), 'exists' => $exists, 'selected' => $selected);
        $date->addDays(1);
        //these 2 lines useless? to check
        $ts = $date->getTimeStamp();
        $date->setTimestamp($ts);
    }
    foreach ($return as $key => $r) {
        $row =& $return[$key];
        for ($i = 0; $i < 7; $i++) {
            if (!isset($row[$i])) {
                $row[$i] = "-";
            }
        }
        ksort($row);
    }
    return $return;
}
Пример #15
0
 public static function dayDifference(Date $left, Date $right)
 {
     return gregoriantojd($right->getMonth(), $right->getDay(), $right->getYear()) - gregoriantojd($left->getMonth(), $left->getDay(), $left->getYear());
 }
 function getVisitsFrequencyNewReturningGraph()
 {
     $all = $this->getContent('vis_period');
     switch ($this->archive->periodType) {
         case DB_ARCHIVES_PERIOD_WEEK:
             $typeDateDisplay = 2;
             $typeDateDisplayGraph = 8;
             break;
         case DB_ARCHIVES_PERIOD_MONTH:
             $typeDateDisplay = 2;
             $typeDateDisplayGraph = 8;
             break;
         case DB_ARCHIVES_PERIOD_YEAR:
             $typeDateDisplay = 5;
             $typeDateDisplayGraph = 10;
             break;
     }
     $new = $returning = $axis = array();
     ksort($all);
     foreach ($all as $date => $info) {
         $new[] = $info[ARRAY_INDEX_NEW_COUNT];
         $returning[] = $info[ARRAY_INDEX_RETURNING_COUNT];
         switch ($this->archive->periodType) {
             case DB_ARCHIVES_PERIOD_DAY:
                 $dateD = sprintf($GLOBALS['lang']['generique_tempsheure'], $date);
                 break;
             case DB_ARCHIVES_PERIOD_WEEK:
                 $dateD = getDateDisplay($typeDateDisplayGraph, new Date($date));
                 break;
             case DB_ARCHIVES_PERIOD_MONTH:
                 $dateDD = new Date($date);
                 $dateD = $dateDD->getDay();
                 break;
             case DB_ARCHIVES_PERIOD_YEAR:
                 $dateDD = new Date($date);
                 $dateD = $GLOBALS['lang']['moistab_graph'][$dateDD->getMonth()];
                 break;
         }
         $axis[] = $dateD;
     }
     return array('data1' => array('data' => $new, 'legend' => $GLOBALS['lang']['frequence_nouvellesvisites']), 'data2' => array('data' => $returning, 'legend' => $GLOBALS['lang']['frequence_visitesconnues']), 'axis' => $axis, 'title' => $GLOBALS['lang']['frequence_nouveauxconnus']);
 }
Пример #17
0
function transferFinishedTransactions($account, $plannedTransaction)
{
    $now = new Date();
    $date = new Date($plannedTransaction->getBeginDate());
    $dayOfMonth = $date->getDay();
    //While we are before now and the end date of this transaction
    while (!$date->after($now) && !$date->after(is_null($tmp = $plannedTransaction->getEndDate()) ? new Date('9999-12-31') : $tmp)) {
        $account->addFinishedTransaction($plannedTransaction->getAmount(), $plannedTransaction->getTitle(), $plannedTransaction->getDescription(), new Date($date), $plannedTransaction->getTransactionPartner(), $plannedTransaction->getCategory(), $plannedTransaction->getOutsideCapital(), false, true);
        //do the date calculation
        switch ($plannedTransaction->getRepeatUnit()) {
            case 'day':
                $date->addSeconds($plannedTransaction->getRepeatFrequency() * 24 * 60 * 60);
                break;
            case 'week':
                $date->addSeconds($plannedTransaction->getRepeatFrequency() * 7 * 24 * 60 * 60);
                break;
            case 'month':
                //Set the month
                $date = new Date(Date_Calc::endOfMonthBySpan($plannedTransaction->getRepeatFrequency(), $date->getMonth(), $date->getYear(), '%Y-%m-%d'));
                //And count back as far as the last valid day of this month
                while ($date->getDay() > $dayOfMonth) {
                    $date->subtractSeconds(24 * 60 * 60);
                }
                break;
            case 'year':
                $newYear = $date->getYear() + $plannedTransaction->getRepeatFrequency();
                if ($dayOfMonth == 29 && $date->getMonth() == 2 && !Date_Calc::isLeapYear($newYear)) {
                    $date->setDay(28);
                } else {
                    $date->setDay($dayOfMonth);
                }
                $date->setYear($newYear);
                break;
            default:
                throw new BadgerException('Account', 'IllegalRepeatUnit', $plannedTransaction->getRepeatUnit());
                exit;
        }
    }
}
Пример #18
0
<?php

$date = new Date();
$date->setDMY(1, 4, 2010);
$date->setToLastMonthDay();
echo $date->getDay();
Пример #19
0
 /**
  * Adds a holiday to the driver's holidays
  *
  * @param string $internalName internal name - must not contain characters
  *                              that aren't allowed as variable-names
  * @param mixed  $date         date (timestamp | string | PEAR::Date object)
  * @param string $title        holiday title
  *
  * @access   protected
  * @return   void
  */
 function _addHoliday($internalName, $date, $title)
 {
     if (!is_a($date, 'Date')) {
         $date = new Date($date);
     }
     $this->_dates[$internalName] = $date;
     $this->_titles['C'][$internalName] = $title;
     $isodate = mktime(0, 0, 0, $date->getMonth(), $date->getDay(), $date->getYear());
     if (!isset($this->_holidays[$isodate])) {
         $this->_holidays[$isodate] = array();
     }
     array_push($this->_holidays[$isodate], $internalName);
     array_push($this->_internalNames, $internalName);
 }
Пример #20
0
 /**
  * Build the internal arrays that contain data about holidays.
  *
  * @access   protected
  * @return   boolean true on success, otherwise a PEAR_ErrorStack object
  * @throws   object PEAR_ErrorStack
  */
 function _buildHolidays()
 {
     parent::_buildHolidays();
     /*
      * Labour Day.
      */
     $labourDay = Date_Calc::nWeekdayOfMonth(1, 1, 3, $this->_year);
     $this->_addHoliday('labourDay', $labourDay, "Labour Day");
     /*
      * Foundation Day (Queen's Birthday in other states).
      * See http://en.wikipedia.org/wiki/Queen%27s_Official_Birthday#Australia
      */
     $foundationDay = Date_Calc::nWeekdayOfMonth(1, 1, 6, $this->_year);
     $this->_addHoliday('foundationDay', $foundationDay, "Foundation Day");
     /*
      * The Queen's Birthday.  There is no firm rule to determine this date before
      * it is proclaimed, but it is usually the last Monday of September or the
      * first Monday of October, to fit in with school terms and the Perth Royal
      * Show.  Here we assume that whichever of the two is closest to the start of
      * Octber will be the holiday; this has been verified to be correct up to and
      * including 2013, but dates beyond then should be verified once they've been
      * proclaimed (and something added here to account for historical and future
      * irregularities).
      */
     $y = $this->_year;
     $lastMonSept = new Date(Date_Calc::nWeekdayOfMonth('last', 1, 9, $y));
     $firstMonOct = new Date(Date_Calc::nWeekdayOfMonth(1, 1, 10, $y));
     $daysToEnd = 30 - $lastMonSept->getDay();
     $daysToStart = $firstMonOct->getDay();
     if ($daysToEnd < $daysToStart) {
         $queensBirthday = $lastMonSept;
     } else {
         $queensBirthday = $firstMonOct;
     }
     $this->_addHoliday('queensBirthday', $queensBirthday, "Queen's Birthday");
 }
Пример #21
0
 /**
  * A method to calculate the range of dates that a statistics screen needs to display.
  *
  * Returns an array of values where:
  *
  *  - If "week" or "day" is the breakdown, array is of days, indexed by "YYYY-MM-DD",
  *    and formatted using the user's local format for days.
  *
  *  - If "month" is the breakdown, array is of months, indexed by "YYYY-MM",
  *    and formatted using the user's local format for months and days.
  *
  *  - If "dow" is the breakdown, array is of days of the week, indexed by the integers
  *    0 to 6, and formatted with the user's local weekday names.
  *
  *  - If "hour" is the breakdown, array is of hours of the day, indexed by the integers
  *    0 to 23, and formatted in the format "00:00 - 00:59", "01:00 01:59", etc.
  *
  * @param array      $aDates          An array of the start and end dates in use by the day
  *                                    span selector element, if set.
  * @param string     $breakdown       The breakdown type in use. One of "week", "day", "month",
  *                                    "dow" or "hour".
  * @param PEAR::Date $oStatsStartDate A date object representing the first day of statistics
  *                                    that are available.
  * @return array The array, as described above.
  */
 function getDatesArray($aDates, $breakdown, $oStatsStartDate)
 {
     // Does the day span selector element have dates set?
     if ($aDates['day_begin'] && $aDates['day_end'] || $aDates['period_start'] && $aDates['period_end']) {
         if ($aDates['day_begin'] && $aDates['day_end']) {
             // Use the dates given by the day span selector element
             $oStartDate = new Date($aDates['day_begin']);
             $oEndDate = new Date($aDates['day_end']);
         } else {
             // Use the dates given by the period_start and period_end
             $oStartDate = new Date($aDates['period_start']);
             $oEndDate = new Date($aDates['period_end']);
         }
         // Adjust end date to be now, if it's in the future
         if ($oEndDate->isFuture()) {
             $oEndDate = new Date();
             $aDates['day_end'] = new Date();
             $aDates['day_end'] = $aDates['day_end']->format('%Y-%m-%d');
         }
     } else {
         // Use the dates given by the statistics date limitation
         // and now
         $oStartDate = new Date();
         $oStartDate->copy($oStatsStartDate);
         $oEndDate = new Date();
     }
     // Prepare the return array
     $aDatesResult = array();
     switch ($breakdown) {
         case 'week':
         case 'day':
             $oOneDaySpan = new Date_Span('1', '%d');
             $oEndDate->addSpan($oOneDaySpan);
             $oDate = new Date();
             $oDate->copy($oStartDate);
             while ($oDate->before($oEndDate)) {
                 $aDatesResult[$oDate->format('%Y-%m-%d')] = $oDate->format($GLOBALS['date_format']);
                 $oDate->addSpan($oOneDaySpan);
             }
             break;
         case 'month':
             $oOneMonthSpan = new Date_Span((string) ($oEndDate->getDaysInMonth() - $oEndDate->getDay() + 1), '%d');
             $oEndDate->addSpan($oOneMonthSpan);
             $oDate = new Date();
             $oDate->copy($oStartDate);
             while ($oDate->before($oEndDate)) {
                 $aDatesResult[$oDate->format('%Y-%m')] = $oDate->format($GLOBALS['month_format']);
                 $oOneMonthSpan = new Date_Span((string) ($oDate->getDaysInMonth() - $oDate->getDay() + 1), '%d');
                 $oDate->addSpan($oOneMonthSpan);
             }
             break;
         case 'dow':
             for ($dow = 0; $dow < 7; $dow++) {
                 $aDatesResult[$dow] = $GLOBALS['strDayFullNames'][$dow];
             }
             break;
         case 'hour':
             for ($hour = 0; $hour < 24; $hour++) {
                 $aDatesResult[$hour] = sprintf('%02d:00 - %02d:59', $hour, $hour);
             }
             break;
     }
     return $aDatesResult;
 }
Пример #22
0
 /**
  * A method to get the number of operation intervals in a given
  * start & end date range must be valid OI start & end date range
  *
  * @static
  * @param object $oStartDate PEAR::Date object
  * @param object $oEndDate PEAR::Date object
  * @return integer number of operation intervals remaining
  */
 function getIntervalsRemaining($oStartDate, $oEndDate)
 {
     $operationIntervalSeconds = OX_OperationInterval::getOperationInterval() * 60;
     // Convert to UTC
     $oStartCopy = new Date($oStartDate);
     $oStartCopy->toUTC();
     $oEndCopy = new Date($oEndDate);
     $oEndCopy->toUTC();
     // Get timestamp of start date/time - in seconds
     $startDateSeconds = mktime($oStartCopy->getHour(), $oStartCopy->getMinute(), $oStartCopy->getSecond(), $oStartCopy->getMonth(), $oStartCopy->getDay(), $oStartCopy->getYear());
     // Get timestamp of end date/time - in seconds
     $endDateSeconds = mktime($oEndCopy->getHour(), $oEndCopy->getMinute(), $oEndCopy->getSecond(), $oEndCopy->getMonth(), $oEndCopy->getDay(), $oEndCopy->getYear());
     // calculate interval length in seconds
     $interval = $endDateSeconds - $startDateSeconds;
     // find number of operation intervals during interval
     return $interval <= 0 ? 0 : round($interval / $operationIntervalSeconds);
 }
Пример #23
0
 /**
  * Expands the planned transactions.
  * 
  * All occurences of planned transactions between now and the targetFutureCalcDate will be inserted
  * in finishedTransactions. For distinction the planned transactions will have a 'p' as first character
  * in their id.
  * 
  * @throws BadgerException If an illegal repeat unit is used.
  */
 public function expandPlannedTransactions()
 {
     $now = new Date();
     $now->setHour(0);
     $now->setMinute(0);
     $now->setSecond(0);
     foreach ($this->plannedTransactions as $currentTransaction) {
         $date = new Date($currentTransaction->getBeginDate());
         $dayOfMonth = $date->getDay();
         //While we have not reached targetFutureCalcDate
         while ($this->targetFutureCalcDate->after($date) && !$date->after(is_null($tmp = $currentTransaction->getEndDate()) ? new Date('9999-12-31') : $tmp)) {
             $inRange = true;
             //Check if there is one or more valutaDate filter and apply them
             foreach ($this->filter as $currentFilter) {
                 if ($currentFilter['key'] == 'valutaDate') {
                     switch ($currentFilter['op']) {
                         case 'eq':
                             if (Date::compare($date, $currentFilter['val']) != 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'lt':
                             if (Date::compare($date, $currentFilter['val']) >= 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'le':
                             if (Date::compare($date, $currentFilter['val']) > 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'gt':
                             if (Date::compare($date, $currentFilter['val']) <= 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'ge':
                             if (Date::compare($date, $currentFilter['val']) < 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'ne':
                             if (Date::compare($date, $currentFilter['val']) == 0) {
                                 $inRange = false;
                             }
                             break;
                         case 'bw':
                         case 'ew':
                         case 'ct':
                             if (strncasecmp($date->getFormatted(), $currentFilter['val']->getFormatted(), 9999) != 0) {
                                 $inRange = false;
                             }
                             break;
                     }
                     if (!$inRange) {
                         break;
                     }
                 }
             }
             if (!$date->before($now) && $inRange) {
                 $this->finishedTransactions[] = new FinishedTransaction($this->badgerDb, $this, 'p' . $currentTransaction->getId() . '_' . $date->getDate(), $currentTransaction->getTitle(), $currentTransaction->getAmount(), $currentTransaction->getDescription(), new Date($date), $currentTransaction->getTransactionPartner(), $currentTransaction->getCategory(), $currentTransaction->getOutsideCapital(), false, true, $currentTransaction, 'PlannedTransaction');
             }
             //do the date calculation
             switch ($currentTransaction->getRepeatUnit()) {
                 case 'day':
                     $date->addSeconds($currentTransaction->getRepeatFrequency() * 24 * 60 * 60);
                     break;
                 case 'week':
                     $date->addSeconds($currentTransaction->getRepeatFrequency() * 7 * 24 * 60 * 60);
                     break;
                 case 'month':
                     //Set the month
                     $date = new Date(Date_Calc::endOfMonthBySpan($currentTransaction->getRepeatFrequency(), $date->getMonth(), $date->getYear(), '%Y-%m-%d'));
                     //And count back as far as the last valid day of this month
                     while ($date->getDay() > $dayOfMonth) {
                         $date->subtractSeconds(24 * 60 * 60);
                     }
                     break;
                 case 'year':
                     $newYear = $date->getYear() + $currentTransaction->getRepeatFrequency();
                     if ($dayOfMonth == 29 && $date->getMonth() == 2 && !Date_Calc::isLeapYear($newYear)) {
                         $date->setDay(28);
                     } else {
                         $date->setDay($dayOfMonth);
                     }
                     $date->setYear($newYear);
                     break;
                 default:
                     throw new BadgerException('Account', 'IllegalRepeatUnit', $currentTransaction->getRepeatUnit());
                     exit;
             }
         }
     }
 }
 private function previousOccurence($date, $start = null)
 {
     if (is_null($start)) {
         $start = $this->beginDate;
     }
     $dayOfMonth = $start->getDay();
     //do the date calculation
     switch ($this->repeatUnit) {
         case 'day':
             $date->subtractSeconds($this->repeatFrequency * 24 * 60 * 60);
             break;
         case 'week':
             $date->subtractSeconds($this->repeatFrequency * 7 * 24 * 60 * 60);
             break;
         case 'month':
             //Set the month
             $date = new Date(Date_Calc::endOfMonthBySpan(-$this->repeatFrequency, $date->getMonth(), $date->getYear(), '%Y-%m-%d'));
             //And count back as far as the last valid day of this month
             while ($date->getDay() > $dayOfMonth) {
                 $date->subtractSeconds(24 * 60 * 60);
             }
             break;
         case 'year':
             $newYear = $date->getYear() - $this->repeatFrequency;
             if ($dayOfMonth == 29 && $date->getMonth() == 2 && !Date_Calc::isLeapYear($newYear)) {
                 $date->setDay(28);
             } else {
                 $date->setDay($dayOfMonth);
             }
             $date->setYear($newYear);
             break;
         default:
             throw new BadgerException('Account', 'IllegalRepeatUnit', $this->repeatUnit);
             exit;
     }
     //switch
     return $date;
 }
Пример #25
0
function fitnesslog_widget_summary_prior_years($args)
{
    $display = new Date();
    $display->setDayMonthYear($display->getDay(), $display->getMonth(), $display->getYear() - 1);
    // Get the arguments passed to the widget.
    extract($args);
    echo $before_widget;
    echo $before_title;
    echo $display->format("%Y");
    echo ' Totals';
    echo $after_title;
    echo '<ul>';
    $result = get_summary_totals("s", "py");
    if ($result) {
        echo '<li>Swim: ';
        echo get_summary_totals("s", "py");
        echo '</li>';
    }
    $result = get_summary_totals("b", "py");
    if ($result) {
        echo '<li>Bike: ';
        echo get_summary_totals("b", "py");
        echo '</li>';
    }
    $result = get_summary_totals("r", "py");
    if ($result) {
        echo '<li>Run: ';
        echo get_summary_totals("r", "py");
        echo '</li>';
    }
    $result = get_summary_totals("str", "py");
    if ($result) {
        echo '<li>Strength: ';
        echo get_summary_totals("str", "py");
        echo '</li>';
    }
    echo '</ul>';
    echo $after_widget;
}
Пример #26
0
 /**
  * Set a given timezone for the passed date. Really modifies
  * the date as just the timezone is exchanged, no further
  * modifications are done.
  *
  * @param   util.Date date
  * @param   util.TimeZone tz
  * @return  util.Date
  */
 public static function setTimezone(Date $date, TimeZone $tz)
 {
     return Date::create($date->getYear(), $date->getMonth(), $date->getDay(), $date->getHours(), $date->getMinutes(), $date->getSeconds(), $tz);
 }
Пример #27
0
 /**
  * DB_DataObject_FormBuilder::_date2array()
  *
  * Takes a string representing a date or a unix timestamp and turns it into an
  * array suitable for use with the QuickForm data element.
  * When using a string, make sure the format can be handled by the PEAR::Date constructor!
  *
  * Beware: For the date conversion to work, you must at least use the letters "d", "m" and "Y" in
  * your format string (see "dateElementFormat" option). If you want to enter a time as well,
  * you will have to use "H", "i" and "s" as well. Other letters will not work! Exception: You can
  * also use "M" instead of "m" if you want plain text month names.
  *
  * @param mixed $date   A unix timestamp or the string representation of a date, compatible to strtotime()
  * @return array
  * @access protected
  */
 function _date2array($date)
 {
     $da = array();
     if (is_string($date)) {
         if (preg_match('/^\\d+:\\d+(:\\d+|)(\\s+[ap]m|)$/i', $date)) {
             $date = date('Y-m-d ') . $date;
             $getDate = false;
         } else {
             $getDate = true;
         }
         include_once 'Date.php';
         $dObj = new Date($date);
         if ($getDate) {
             $da['d'] = $dObj->getDay();
             $da['l'] = $da['D'] = $dObj->getDayOfWeek();
             $da['m'] = $da['M'] = $da['F'] = $dObj->getMonth();
             $da['Y'] = $da['y'] = $dObj->getYear();
         }
         $da['H'] = $dObj->getHour();
         $da['h'] = $da['H'] % 12;
         if ($da['h'] == 0) {
             $da['h'] = 12;
         }
         $da['g'] = $da['h'];
         $da['i'] = $dObj->getMinute();
         $da['s'] = $dObj->getSecond();
         if ($da['H'] >= 12) {
             $da['a'] = 'pm';
             $da['A'] = 'PM';
         } else {
             $da['a'] = 'am';
             $da['A'] = 'AM';
         }
         unset($dObj);
     } else {
         if (is_int($date)) {
             $time = $date;
         } else {
             $time = time();
         }
         $da['d'] = date('d', $time);
         $da['l'] = $da['D'] = date('w', $time);
         $da['m'] = $da['M'] = $da['F'] = date('m', $time);
         $da['Y'] = $da['y'] = date('Y', $time);
         $da['H'] = date('H', $time);
         $da['g'] = date('g', $time);
         $da['h'] = date('h', $time);
         $da['i'] = date('i', $time);
         $da['s'] = date('s', $time);
         $da['a'] = date('a', $time);
         $da['A'] = date('A', $time);
     }
     DB_DataObject_FormBuilder::debug('<i>_date2array():</i> from ' . $date . ' to ' . serialize($da) . ' ...');
     return $da;
 }
Пример #28
0
 private function datePicker(Date $dateObj)
 {
     $yStart = empty($this->yearStart) ? "-3" : $this->yearStart;
     $yEnd = empty($this->yearEnd) ? "+3" : $this->yearEnd;
     return $this->ascList("d", 1, 31, $dateObj->getDay()) . $this->ascList("m", 1, 12, $dateObj->getMonth()) . $this->ascList("y", $this->getEvaledYear($yStart), $this->getEvaledYear($yEnd), $dateObj->getYear());
 }
Пример #29
0
 public function getNextRunTime($date)
 {
     // check if $date is a timestamp...
     if ($date instanceof Date == false && is_integer($date)) {
         $date = new Date($date);
     }
     // assume now $date IS instanceof Date
     $cSecond = $date->getSecond();
     $cMinute = $date->getMinute();
     $cHour = $date->getHour();
     $cDay = $date->getDay();
     $cMonth = $date->getMonth();
     $cYear = $date->getYear();
     // required to check the number of days in the month
     $found = false;
     while ($found === false) {
         while ($found === false) {
             // iterate months...
             $cMonth = $this->findNextInArray($cMonth, $this->monthArray);
             if ($cMonth === null) {
                 break;
             }
             // find the day now
             while ($found === false) {
                 $cDay = $this->findNextInArray($cDay, $this->dayArray);
                 if ($cDay === null) {
                     break;
                 }
                 // here dayOfWeek and number of days in month should be checked!
                 $date = new Date();
                 $date->setYear($cYear);
                 $date->setMonth($cMonth);
                 $numberOfDaysInMonth = $date->getDaysInMonth();
                 if ($cDay > $numberOfDaysInMonth) {
                     break;
                 }
                 if ($this->dayOfWeekArray !== null) {
                     // get day of the week
                     $date->setDay($cDay);
                     $dayOfWeek = $date->getDayOfWeek();
                     if (!in_array($dayOfWeek, $this->dayOfWeekArray)) {
                         $cDay++;
                         continue;
                     }
                 }
                 while ($found === false) {
                     if ($cHour == 24) {
                         break;
                     }
                     $cHour = $this->findNextInArray($cHour, $this->hourArray);
                     if ($cHour === null) {
                         break;
                     }
                     while ($found === false) {
                         if ($cMinute == 60) {
                             break;
                         }
                         $cMinute = $this->findNextInArray($cMinute, $this->minuteArray);
                         if ($cMinute === null) {
                             break;
                         }
                         while ($found === false) {
                             if ($cSecond == 60) {
                                 break;
                             }
                             $cSecond = $this->findNextInArray($cSecond, $this->secondArray);
                             if ($cSecond === null) {
                                 break;
                             } else {
                                 // FOUND IT!!! WOOOO!
                                 // create Date object
                                 $date = new Date();
                                 $date->setYear($cYear);
                                 $date->setMonth($cMonth);
                                 $date->setDay($cDay);
                                 $date->setHour($cHour);
                                 $date->setMinute($cMinute);
                                 $date->setSecond($cSecond);
                                 return $date;
                             }
                         }
                         $cMinute++;
                         $cSecond = 0;
                     }
                     $cHour++;
                     $cMinute = 0;
                     $cSecond = 0;
                 }
                 $cDay++;
                 $cHour = 0;
                 $cMinute = 0;
                 $cSecond = 0;
             }
             $cMonth++;
             $cDay = 0;
             $cHour = 0;
             $cMinute = 0;
             $cSecond = 0;
         }
         $cYear++;
         $cMonth = 0;
         $cDay = 0;
         $cHour = 0;
         $cMinute = 0;
         $cSecond = 0;
     }
 }
 public static function getHumanDay(Date $date, $wordDayNeed = true)
 {
     $today = Date::makeToday();
     $tomorrow = $today->spawn('+1 day');
     if ($date->toDate() == $today->toDate() && $wordDayNeed == true) {
         return 'сегодня';
     } elseif ($date->toDate() == $tomorrow->toDate() && $wordDayNeed == true) {
         return 'завтра';
     } else {
         return (int) $date->getDay() . ' ' . RussianTextUtils::getMonthInGenitiveCase($date->getMonth());
     }
 }