/** * Constructor * * @param string $start The start date of the period 'YYYY-mm-dd' * @param string $end optional End date * @param string $timezone optional Timezone * @throws \InvalidArgumentException */ public function __construct($start, $end = null, $timezone = 'UTC') { $this->mode = 'day'; $this->timezone = new DateTimeZone($timezone); $this->today = $this->getTodayDate(); $this->start = new DateTime($start instanceof DateTime ? $start->format('Y-m-d 00:00:00') : $start, $this->timezone); $this->end = !empty($end) ? new DateTime($end instanceof DateTime ? $end->format('Y-m-d 00:00:00') : $end, $this->timezone) : null; //Difference in days between Start and End dates $diffdays = $this->start->diff($this->end, true)->days; //Difference in days between Start and Today dates $diffTodayDays = $this->start->diff($this->today, true)->days; //Previous interval is the same period in the past $this->prevInterval = new \DateInterval('P' . ($diffdays + 1) . 'D'); if ($diffdays < 2 && $diffTodayDays < 14) { $this->interval = '1 hour'; } else { $this->interval = '1 day'; } $this->prevStart = clone $this->start; $this->prevStart->sub($this->prevInterval); $this->wholePeriodPerviousEnd = clone $this->start; $this->wholePeriodPerviousEnd->modify('-1 day'); $this->prevEnd = clone $this->prevStart; $this->prevEnd->add(new \DateInterval('P' . $this->start->diff(min($this->end, $this->today), true)->days . 'D')); $endoftheday = new \DateInterval('PT23H59M59S'); $this->end->add($endoftheday); $this->prevEnd->add($endoftheday); $this->wholePeriodPerviousEnd->add($endoftheday); if (!$this->di) { $this->di = \DateInterval::createFromDateString($this->interval); } $this->dt = clone $this->start; }
static function createDateString($dateString = 'yesterday') { global $gTimezone; $date = new \DateTime('now', new \DateTimeZone($gTimezone)); $date->add(\DateInterval::createFromDateString($dateString)); return $date->format('Ymd'); }
/** * Constructor * * @param string $start The start date of the period 'YYYY-mm-dd' * @param string $end optional End date * @param string $timezone optional Timezone * @throws \InvalidArgumentException */ public function __construct($start, $end = null, $timezone = 'UTC') { $this->mode = 'week'; $this->timezone = new DateTimeZone($timezone); $this->today = $this->getTodayDate(); $this->start = new DateTime($start instanceof DateTime ? $start->format('Y-m-d 00:00:00') : $start, $this->timezone); $this->end = !empty($end) ? new DateTime($end instanceof DateTime ? $end->format('Y-m-d 00:00:00') : $end, $this->timezone) : null; //Week should start from sunday if ($this->start->format('w') != 0) { $this->start->modify('last sunday'); } $this->prevInterval = new \DateInterval('P7D'); //Each point $this->interval = '1 day'; $this->end = clone $this->start; $this->end->add(new \DateInterval('P6D')); $this->prevStart = clone $this->start; $this->prevStart->sub($this->prevInterval); $this->wholePeriodPerviousEnd = clone $this->start; $this->wholePeriodPerviousEnd->modify('-1 day'); $this->prevEnd = clone $this->prevStart; $this->prevEnd->add(new \DateInterval('P' . $this->start->diff(min($this->end, $this->today), true)->days . 'D')); $endoftheday = new \DateInterval('PT23H59M59S'); $this->end->add($endoftheday); $this->prevEnd->add($endoftheday); $this->wholePeriodPerviousEnd->add($endoftheday); if (!$this->di) { $this->di = \DateInterval::createFromDateString($this->interval); } $this->dt = clone $this->start; }
public function getAppOnlineTime($device_id, $apps, $days = 3) { if (!$apps) { return $apps; } $ids = []; foreach ($apps as $app) { $ids[] = $app->id; } $now = new \DateTime(); $now->sub(\DateInterval::createFromDateString("{$days} days")); $where = ['status' => 'ACTIVE', 'downloads.create_date > ?' => $now->format('Y-m-d') . ' 00:00:00', "downloads.device_id" => $device_id]; if ($ids) { $where['downloads.app_id in (' . substr(str_pad('', count($ids) * 2, ',?'), 1) . ')'] = $ids; } $downloads = $this->select('downloads.app_id')->from('downloads')->where($where)->groupBy('downloads.app_id')->result(); $app_ids = []; foreach ($downloads as $download) { $app_ids[$download->app_id] = $download->app_id; } foreach ($apps as $app) { if (isset($app_ids[$app->id])) { $app->online_time = 0; $app->online_time_action = '0小时'; } } return $apps; }
private function fetchURL($forceRefresh) { $cachedFilePath = $this->cachingLocation + "/" + substr($URL, strrchr($URL, "/")); if (!$forceRefresh) { if (!file_exists($cachedFilePath)) { $content = file_get_contents($URL); file_put_contents($cachedFilePath, $content); } else { $cacheTTL = DateInterval::createFromDateString("15 minutes"); $fetchingDelay = DateInterval::createFromDateString("5 minutes"); $cacheAge = getdate(time() - filemtime($cachedFilePath)); if ($cacheAge["minutes"] >= $cacheTTL) { // Is cache expired unlink($cachedFilePath); // Just some housekeeping code, that may not be necessary $content = file_get_contents($URL); file_put_contents($cachedFilePath, $content); return $content; } else { return file_get_contents($cachedFilePath); } } } else { unlink($cachedFilePath); // Just some housekeeping code, that may not be necessary $content = file_get_contents($URL); file_put_contents($cachedFilePath, $content); return $content; } }
function smarty_function_oauth_wechat($params, $template) { $label = lang('Wechat'); $check = check_need_to_show('MicroMessenger'); switch ($check) { case 0: return ''; break; case 2: $label = lang('Let Me Online'); break; } $type = 'wechat'; $CI =& get_instance(); $CI->load->model(array('login_model', 'user_social_app_model')); $args = $CI->login_model->getLoginArgs(); if (isset($args->appid)) { $oauth_info = $CI->user_social_app_model->getSocialAppByType($args->appid, $type); if (isset($oauth_info->appid) && $oauth_info->appid) { unset($params['uri']); if ($check == 1 && isset($args->serial) && isset($args->gateway_ip) && isset($args->gateway_port) && isset($args->ip) && isset($args->mac)) { $CI->load->library('encryptor'); $now = new DateTime(); $expire = new DateTime(); $expire->add(DateInterval::createFromDateString('5 minute')); $token = $CI->encryptor->encrypt(json_encode(array('uid' => 'activate', 'createDate' => $now->getTimestamp(), 'expireDate' => $expire->getTimestamp()))); return anchor('http://' . $args->gateway_ip . ':' . $args->gateway_port . '/pinet/auth?token=' . urlencode($token) . '&url=' . urlencode('http://www.pinet.co/auth/tip'), $label, $params); } return anchor(site_url('oauth/session/' . $type . '/' . $args->appid), $label, $params); } } return ''; }
/** * {@inheritdoc} */ public function authenticate($key, $code, \DateTime $timestampToCheck = null) { $timestampToCheck = $timestampToCheck ?: new \DateTime(); if ($this->blacklist->contains($key, $code)) { return false; } $timeStep = $this->generator->getTimeStep(); $lookAroundSeconds = (int) ($this->lookAround * $timeStep); $interval = \DateInterval::createFromDateString($lookAroundSeconds . ' seconds'); $start = clone $timestampToCheck; $start->sub($interval); $end = clone $timestampToCheck; $end->add($interval); $modification = '+ ' . $timeStep . ' seconds'; for ($timestamp = $start; $timestamp <= $end; $timestamp->modify($modification)) { $generatedCode = $this->generator->generateCode($key, strlen($code), $timestamp); if ($generatedCode === $code) { $this->blacklist->add($key, $code); return true; } if (!$this->lookAround) { break; } } $this->blacklist->add($key, $code); return false; }
/** * Constructor * * @param string $start The start date of the period 'YYYY-mm-dd' * @param string $end optional End date * @param string $timezone optional Timezone * @throws \InvalidArgumentException */ public function __construct($start, $end = null, $timezone = 'UTC') { $this->mode = 'month'; $this->timezone = new DateTimeZone($timezone); $this->today = $this->getTodayDate(); $this->start = new DateTime($start instanceof DateTime ? $start->format('Y-m-d 00:00:00') : $start, $this->timezone); $this->end = !empty($end) ? new DateTime($end instanceof DateTime ? $end->format('Y-m-d 00:00:00') : $end, $this->timezone) : null; //Previous period is the previous month started from the the first day of the month $this->prevInterval = new \DateInterval('P1M'); $this->interval = '1 day'; $this->start = new DateTime($this->start->format('Y-m-01'), $this->timezone); $this->end = new DateTime($this->start->format('Y-m-t'), $this->timezone); $this->prevStart = clone $this->start; $this->prevStart->sub($this->prevInterval); $this->wholePeriodPerviousEnd = clone $this->prevStart; $this->wholePeriodPerviousEnd->modify('last day of this month'); $this->determinePrevEnd(); $endoftheday = new \DateInterval('PT23H59M59S'); $this->end->add($endoftheday); $this->prevEnd->add($endoftheday); $this->wholePeriodPerviousEnd->add($endoftheday); if (!$this->di) { $this->di = \DateInterval::createFromDateString($this->interval); } $this->dt = clone $this->start; }
/** * Returns the element's status. * * @return string|null */ public function getStatus() { $currentTime = DateTimeHelper::currentTimeStamp(); $startDate = $this->startDate ? $this->startDate->getTimestamp() : null; $endDate = $this->endDate ? $this->endDate->getTimestamp() : null; $pluginSettings = craft()->plugins->getPlugin('maintenance')->pluginSettings; $interval = $pluginSettings['maintenanceImminent']; $interval = DateInterval::createFromDateString($interval); $secondsInAdvance = (new DateTime('@0'))->add($interval)->getTimeStamp(); if (!$startDate) { return static::NONE; } if (!$this->blockCp && !$this->blockSite) { return static::DISABLED; } else { if ($startDate > $currentTime) { if ($startDate > $currentTime + $secondsInAdvance) { return static::PENDING; } else { return static::IMMINENT; } } else { if ($startDate <= $currentTime && (!$endDate || $endDate > $currentTime)) { return static::INPROGRESS; } else { if ($startDate <= $currentTime) { return static::COMPLETED; } } } } }
/** * @dataProvider useCases * * @param $config */ public function test_UseCase($config) { date_default_timezone_set($config['timezone']); $timezone = new DateTimeZone($config['timezone']); $start = new DateTime($config['start'], $timezone); $end = new DateTime($config['end'], $timezone); $storage = new Storage(); $storage->setDefaultMiddleware($this->conn, new Logger(null)); $pipelineFactory = new Factory($this->conn); $pipeline = new Pipeline(); $cvs = []; $dateperiod = new DatePeriod($start, DateInterval::createFromDateString($config['insertResolution'] . ' seconds'), $end); foreach ($dateperiod as $datetime) { $cvs[] = new CounterValue($config['sid'], $config['nid'], $datetime, $config['val'], $config['incremental']); } $storage->store($cvs); $sequence = $pipelineFactory->createMultiAction($config['sid'], $config['nid'], $start, $end, $config['retrieveResolution'], $config['aggregation']); $sequence[] = new ConvertToDateStringKeys(); $valsByDate = $pipeline->run($sequence); $msg = $config['description']; $msg .= "\nExpected\n"; $msg .= json_encode($config['expected'], JSON_PRETTY_PRINT); $msg .= "\nActual:\n"; $msg .= json_encode($valsByDate, JSON_PRETTY_PRINT); $this->assertTrue($valsByDate === $config['expected'], $msg); }
private function getDurationsByUser(WakaUser $user) { $settings = new Settings(); $settings->username = $user->username; $settings->password = $user->password; $waka = new Client($settings); $now = $this->time->now(); $weekAgo = $now - 7 * 86400; $lastFetch = $user->lastFetch; if (!$lastFetch) { $lastFetch = $weekAgo; } $today = date('Y-m-d', $now); $lastDate = date('Y-m-d', $lastFetch); if ($today > $lastDate) { $begin = new \DateTime($lastDate); $end = new \DateTime($today); $interval = \DateInterval::createFromDateString('1 day'); $period = new \DatePeriod($begin, $interval, $end); /** @var \DateTime $dt */ foreach ($period as $dt) { $date = $dt->format("Y-m-d"); echo $date, PHP_EOL; $this->getDurationsByUserAndDate($user, $waka, $date); $user->lastFetch = strtotime($date); $user->save(); } } }
/** * @return \DateTime */ protected function createExpirationDate() { $dateInterval = \DateInterval::createFromDateString($this->omsConfig->getStateMachineLockerTimeoutInterval()); $expirationDate = new \DateTime(); $expirationDate->add($dateInterval); return $expirationDate; }
public function test_FiveMinResolutionSumTwoSeries_RollupSpace_ReturnSumForBothSeries() { $value1 = 10; $value2 = 20; $nDays = 20; $aggregation = Aggregation::SUM; $start = new DateTIme('2015-10-10 00:00:00'); $end = clone $start; $end->add(DateInterval::createFromDateString($nDays . ' days')); $dateperiod = new DatePeriod($start, DateInterval::createFromDateString('5 minutes'), $end); $vals1 = []; $vals2 = []; $expected = []; foreach ($dateperiod as $datetime) { $vals1[$datetime->getTimestamp()] = $value1; $vals2[$datetime->getTimestamp()] = $value2; $expected[$datetime->format('Y-m-d H:i:s')] = $value1 + $value2; } $series1 = new Series($vals1); $series2 = new Series($vals2); $convert = new ConvertToDateStringKeys(); $action = new RollupSpace($aggregation); $output = $action->run([$series1, $series2]); $output = $convert->run($output); $this->assertEquals($expected, $output); }
protected function setHistory($history = '-1 week') { $now = new \DateTime(); $prev = new \DateTime(); $prev->add(\DateInterval::createFromDateString($history)); $this->date = array($now, $prev); }
function a(DateTime $start, DateTime $end) { $interval = DateInterval::createFromDateString('1 day'); $period = new DatePeriod($start, $interval, 1); $period = new DatePeriod($start, $interval, $end); $period = new DatePeriod('P1D'); }
public function ibox_status_summary() { $begin = null; $end = null; $mode = 'day'; $beginTime = new DateTime(); $beginTime->sub(DateInterval::createFromDateString('1 month')); $endTime = new DateTime(); if (!isset($_POST['__nouse__'])) { $begin = $this->input->post('begin'); $end = $this->input->post('end'); $mode = $this->input->post('mode'); switch ($mode) { case 'month': $this->setState('month', 'status'); break; case 'week': $this->setState('week', 'status'); break; } $beginTime = parse_datetime($begin, $beginTime); $endTime = parse_datetime($end, $endTime); } $heart_beat_rate = get_ci_config('heart_beat_rate'); $diff = ($endTime->getTimestamp() - $beginTime->getTimestamp()) / 60 / $heart_beat_rate; $user_id = $this->user_model->getLoginUserID(); $this->jquery_mousewheel(); $this->less('business/ibox_status_summary_css'); $this->render('business/ibox_status_summary', array('form_data' => $this->_buildSearches($begin, $end, $mode), 'args' => array($user_id), 'online_args' => array($heart_beat_rate, $diff, $user_id), 'begin' => $begin, 'end' => $end, 'mode' => $mode)); }
public function test_FiveMinResolutionDailySum_RollupTime_ReturnSumForEachDay() { $value = 1; $nDays = 20; $resolution = Resolution::DAY; $aggregation = Aggregation::SUM; $start = new DateTIme('2015-10-10 00:00:00'); $end = clone $start; $end->add(DateInterval::createFromDateString($nDays . ' days')); $dateperiodExpected = new DatePeriod($start, DateInterval::createFromDateString('1 day'), $end); $expected = []; foreach ($dateperiodExpected as $datetime) { $expected[$datetime->format('Y-m-d H:i:s')] = $value * (86400 / $resolution); } $dateperiod = new DatePeriod($start, DateInterval::createFromDateString($resolution . ' seconds'), $end); $valsByTimestamp = []; foreach ($dateperiod as $datetime) { $valsByTimestamp[$datetime->getTimestamp()] = $value; } $series = new Series($valsByTimestamp); $convert = new ConvertToDateStringKeys(); $action = new RollupTime($resolution, $aggregation); $output = $action->run($series); $output = $convert->run($output); $this->assertEquals($expected, $output); }
/** * Check if the time limit is up * * @param DateTime $started Start time * * @return boolean True if the time limit is up */ public function isPassed(\DateTime $started) { // Create a new datetime to now, subtract the limit from it and see if its less than started $now = new \DateTime(); $now->sub(\DateInterval::createFromDateString(sprintf('%d seconds', $this->timeLimit))); return $now >= $started; }
/** * @param string $time * @return \DateInterval */ public static function createFromDateString($time) { $interval = parent::createFromDateString($time); $interval->u = 0; // should be implemented return $interval; }
function action_save() { global $current_user; //Get users date format $dateformat = $current_user->getPreference('datef'); //create datetime objects $startdate = DateTime::createFromFormat($dateformat, $_REQUEST['holiday_start_date']); $enddate = DateTime::createFromFormat($dateformat, $_REQUEST['holiday_end_date']); $enddate->modify('+1 day'); //1 day has to be added to include the last day as a holiday //Create an array of days between the start and end dates $interval = DateInterval::createFromDateString('1 day'); $period = new DatePeriod($startdate, $interval, $enddate); //loop through days and save new holiday record for each day. foreach ($period as $dt) { //format to default mysql date format $holiday_day = $dt->format('Y-m-d'); $this->bean = new AM_ProjectHolidays(); $this->bean->name = $_REQUEST['name']; $this->bean->description = $_REQUEST['description']; $this->bean->resourse_users = $_REQUEST['resourse_users']; $this->bean->holiday_date = $holiday_day; $this->bean->save(); } }
/** * Performs dates arithmetic * * @param string $interval * Each duration period is represented by an integer value followed by a period * designator. If the duration contains time elements, that portion of the * specification is preceded by the letter T. * Period Designators: Y - years, M - months, D - days, W - weeks, H - hours, * M - minutes, S - seconds. * Examples: two days - 2D, two seconds - T2S, six years and five minutes - 6YT5M. * The unit types must be entered from the largest scale unit on the left to the * smallest scale unit on the right. * Use first "-" char for negative periods. * OR * Relative period. * Examples: "+5 weeks", "12 day", "-7 weekdays", '3 months - 5 days' * * @return Date */ public function add($interval) { $i = null; try { $intervalTmp = strtoupper($interval); $isNegative = false; $firstChar = substr($intervalTmp, 0, 1); if ($firstChar === "-") { $isNegative = true; $intervalTmp = substr($intervalTmp, 1); $firstChar = substr($intervalTmp, 0, 1); } if ($firstChar !== "P") { $intervalTmp = "P" . $intervalTmp; } $i = new \DateInterval($intervalTmp); if ($isNegative) { $i->invert = 1; } } catch (\Exception $e) { } if ($i == null) { $i = \DateInterval::createFromDateString($interval); } $this->value->add($i); return $this; }
/** * Generate chart * * @return array */ public function toArray() { $data = array(); $statistics = $this->getRepository()->getStatistics(); $commitsByContributor = $statistics['contributors']->getItems(); foreach ($commitsByContributor as $contributor) { $contributorInfo = null; $begin = new \DateTime($this->getRepository()->getFirstCommitDate()); $end = new \DateTime($this->getRepository()->getLastCommitDate()); $interval = \DateInterval::createFromDateString('1 day'); $period = new \DatePeriod($begin, $interval, $end); $commitsData = array(); $totalCommits = 0; $contributorCommits = $contributor->getItems(); foreach ($period as $date) { $dayFormatted = $date->format("Y-m-d"); $value = isset($contributorCommits[$dayFormatted]) ? count($contributorCommits[$dayFormatted]) : 0; if ($value > 0 && $contributorInfo === null) { $commit = $contributorCommits[$dayFormatted][0]; $contributorInfo = array('name' => $commit->getAuthor()->getName(), 'email' => $commit->getAuthor()->getEmail()); } $totalCommits += $value; $commitsData['x'][] = $dayFormatted; $commitsData['y'][] = $value; } $data[] = array('name' => $contributorInfo['name'], 'email' => $contributorInfo['email'], 'commits' => $totalCommits, 'data' => $commitsData); } usort($data, array($this, 'sortContributorsByCommits')); return $data; }
/** * Subtract given interval from current date time * * @param string $intervalString * * @return \DateTime */ protected function prepareDateInterval($intervalString = null) { $date = new \DateTime('now', new \DateTimeZone('UTC')); $intervalString = $intervalString ?: $this->getContainer()->getParameter('oro_batch.cleanup_interval'); $date->sub(\DateInterval::createFromDateString($intervalString)); return $date; }
/** * Generate the view of the week for given month and given year * with events in this period. * * @param string $year * @param string $week * @return view weekView * * */ public function showWeek($year, $week) { // Create week start date on monday (day 1) $weekStart = date('Y-m-d', strtotime($year . "W" . $week . '1')); // Create the number of the next week $nextWeek = date("W", strtotime("next Week" . $weekStart)); $nextYear = date("Y", strtotime("next Week" . $weekStart)); // Create week end date - we go till tuesday (day 2) because café needs alternative week view (Mi-Di) $weekEnd = date('Y-m-d', strtotime($nextYear . "W" . $nextWeek . '2')); // Create the number of the previous week $previousWeek = date("W", strtotime("previous Week" . $weekStart)); $previousYear = date("Y", strtotime("previous Week" . $weekStart)); // Convert number of prev/next week to verbatim format - needed for correct << and >> button links $nextWeek = $nextYear . "/KW" . $nextWeek; $previousWeek = $previousYear . "/KW" . $previousWeek; $date = array('year' => $year, 'week' => $week, 'weekStart' => $weekStart, 'weekEnd' => $weekEnd, 'nextWeek' => $nextWeek, 'previousWeek' => $previousWeek); $events = ClubEvent::where('evnt_date_start', '>=', $weekStart)->where('evnt_date_start', '<=', $weekEnd)->with('getPlace', 'getSchedule.getEntries.getJobType', 'getSchedule.getEntries.getPerson.getClub')->orderBy('evnt_date_start')->orderBy('evnt_time_start')->get(); $tasks = Schedule::where('schdl_show_in_week_view', '=', '1')->where('schdl_due_date', '>=', $weekStart)->where('schdl_due_date', '<=', $weekEnd)->with('getEntries.getPerson.getClub', 'getEntries.getJobType')->get(); // TODO: don't use raw query, rewrite with eloquent. $persons = Cache::remember('personsForDropDown', 10, function () { $timeSpan = new DateTime("now"); $timeSpan = $timeSpan->sub(DateInterval::createFromDateString('3 months')); return Person::whereRaw("prsn_ldap_id IS NOT NULL \n\t\t\t\t\t\t\t\t\t\t AND (prsn_status IN ('aktiv', 'kandidat') \n\t\t\t\t\t\t\t\t\t\t OR updated_at>='" . $timeSpan->format('Y-m-d H:i:s') . "')")->orderBy('clb_id')->orderBy('prsn_name')->get(); }); $clubs = Club::orderBy('clb_title')->lists('clb_title', 'id'); // IDs of schedules shown, needed for bulk-update $updateIds = array(); foreach ($events as $event) { array_push($updateIds, $event->getSchedule->id); } return View::make('weekView', compact('events', 'schedules', 'date', 'tasks', 'entries', 'weekStart', 'weekEnd', 'persons', 'clubs')); }
public function testTime() { /* This tests multiple formats. Ideally, all the format checking * should be done testing the date helper, but we'll do this * here for now. */ $forum = new Forum(); // Test #1, relative time $forumTime = '7 minutes ago'; $verifyTime = new \DateTime('NOW'); $verifyTime->add(\DateInterval::createFromDateString($forumTime)); $forum->setTime($forumTime); $this->assertEquals($verifyTime->format('Y-m-d\\TH:iO'), $forum->getTime()); // Test #2, partial date (same year) $forumTime = 'Jun 17, 1:01 PM'; $currentTime = new \DateTime('NOW'); $currentYear = $currentTime->format('Y'); $verifyTime = new \DateTime($currentYear . '-06-17 13:01'); $forum->setTime($forumTime); $this->assertEquals($verifyTime->format('Y-m-d\\TH:iO'), $forum->getTime()); // Test #3, full date $forumTime = ' May 1, 2014 1:19 PM'; $verifyTime = new \DateTime('2014-05-01 13:19'); $forum->setTime($forumTime); $this->assertEquals($verifyTime->format('Y-m-d\\TH:iO'), $forum->getTime()); }
/** * Creates the array of daily snapshots in the report. */ protected function loadSnapshots() { $interval = DateInterval::createFromDateString('1 day'); $period = new DatePeriod($this->begin, $interval, $this->end); foreach ($period as $date) { $this->snapshots[$date->format("Y-m-d")] = new FundraiserSustainersDailySnapshot($date); } }
/** * @param array $result * @return \GoogleGlass\Entity\OAuth2\Token */ public function fromArrayResult(array $result) { $this->setAccessToken(isset($result['access_token']) ? $result['access_token'] : null)->setRefreshToken(isset($result['refresh_token']) ? $result['refresh_token'] : null)->setTokenType(isset($result['token_type']) ? $result['token_type'] : null); $date = new \DateTime('now'); $date->add(\DateInterval::createFromDateString("+{$result['expires_in']} seconds")); $this->setExpiresAt($date); return $this; }
public static function generateDayInterval($start, $end) { $startInt = new DateTime($start); $endInt = (new DateTime($end))->modify('+1 day'); $interval = DateInterval::createFromDateString('1 day'); $period = new DatePeriod($startInt, $interval, $endInt); return $period; }
public function testExpiresAtYesterdayIsNotHit() { $item = new Item('my_key'); $item->set(new stdClass()); $yesterday = (new DateTime('now'))->add(DateInterval::createFromDateString('-1 day')); $item->expiresAt($yesterday); $this->assertFalse($item->isHit()); }
/** * Constructor * * @param string $start The start date of the period 'YYYY-mm-dd' * @param string $end optional End date * @param string $timezone optional Timezone * @throws \InvalidArgumentException */ public function __construct($start, $end = null, $timezone = 'UTC') { $this->mode = 'quarter'; $this->timezone = new DateTimeZone($timezone); $this->today = $this->getTodayDate(); $this->start = new DateTime($start instanceof DateTime ? $start->format('Y-m-d 00:00:00') : $start, $this->timezone); $this->end = !empty($end) ? new DateTime($end instanceof DateTime ? $end->format('Y-m-d 00:00:00') : $end, $this->timezone) : null; $quarters = new Quarters(SettingEntity::getQuarters()); $this->interval = '1 week'; $currentPeriod = $quarters->getPeriodForDate($this->start); $this->start = $currentPeriod->start; $this->end = $currentPeriod->end; $this->wholePeriodPerviousEnd = clone $this->start; $this->wholePeriodPerviousEnd->modify('-1 day'); $prevPeriod = $quarters->getPeriodForDate($this->wholePeriodPerviousEnd); $this->prevStart = $prevPeriod->start; $this->prevInterval = new \DateInterval('P' . sprintf("%d", $this->start->diff($this->end, true)->days) . 'D'); $this->determinePrevEnd(); $endoftheday = new \DateInterval('PT23H59M59S'); $this->end->add($endoftheday); $this->prevEnd->add($endoftheday); $this->wholePeriodPerviousEnd->add($endoftheday); if (!$this->di) { $this->di = \DateInterval::createFromDateString($this->interval); } $this->dt = clone $this->start; }