@param $ago
@param null $endDateTime

@return array
4829
public static function getMonthsAgo($ago, $endDateTime = null)
    {
        return static::getDateTimeRange(
            Carbon::now()->subMonths($ago)->startOfMonth(),
            $endDateTime ?: Carbon::now()->subMonths($ago)->endOfMonth()
        );
    }
774153
public function scopeFromMonthsAgo(Builder $query, $ago, $endDateTime = null)
    {
        return $this->scopeFromDateTimeRange(DateTime::getMonthsAgo($ago, $endDateTime));
    }
1313423
public static function initDatetimesInRange($start_datetime, $end_datetime, $hoursDifference = 1){
        $dates_in_range = [];
        $begin = new DateTime($start_datetime);
        $end = new DateTime($end_datetime);
        $endModify = $end->modify( '+'.$hoursDifference.' hour' ); 

        $interval = new DateInterval('PT'.$hoursDifference.'H');
        $daterange = new DatePeriod($begin, $interval ,$endModify);

        foreach($daterange as $date){
            $dates_in_range[$date->getTimestamp()] = $date->format("Y-m-d H:i:s");
        }
        return $dates_in_range;
    }
53936
public static function fromDateTime(DateTime $dateTime)
    {
        $date = new Date();
        $date->setYear(intval($dateTime->format('Y')));
        $date->setMonth(intval($dateTime->format('m')));
        $date->setDay(intval($dateTime->format('d')));

        $result = new AdManagerDateTime();
        $result->setDate($date);
        $result->setHour(intval($dateTime->format('H')));
        $result->setMinute(intval($dateTime->format('i')));
        $result->setSecond(intval($dateTime->format('s')));
        $result->setTimeZoneID($dateTime->format('e'));

        return $result;
    }
1282772
public static function getDateRange4Period(DateTime $beginDate, DateTime $endDate)
    {
        $result = [];
        if ($beginDate < $endDate) {
            do {
                $result[] = clone $beginDate;
                $beginDate->modify('+1 day');
            } while ($beginDate <= $endDate);
        }

        return $result;
    }
343764
public function getListUserCountByRangeDate($types, $startDate = '', $endDate = '')
    {
        if (empty($types)) {
            return array();
        }
        $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');

        $now = new \DateTime("now");
        // $now->format('Y-m-d') . ' 23:59:59';
        $startDateTime = \DateTime::createFromFormat('d/m/Y', $startDate);
        $endDateTime = \DateTime::createFromFormat('d/m/Y', $endDate);

        $rsm = new \Doctrine\ORM\Query\ResultSetMapping;

        $select = array();
        $i = 0;

        foreach ($types as $type) {
            switch ($type) {
                case 'validatedMembers':
                    $filter = "u.state IS NOT NULL";
                    break;
                case 'activeMembers':
                    $filter = "u.state=1";
                    break;
                case 'optin':
                    $filter = "u.optin=1";
                    break;
                case 'optinPartners':
                    $filter = "u.optin_partner=1";
                    break;
                case 'unregistered':
                    $filter = "u.state IS NULL";
                    break;
                case 'suspended':
                    $filter = "u.state=2";
                    break;
                default:
                case 'members':
                    $filter = "u.user_id";
                    break;
            }

            $rsm->addScalarResult('c'.$i, 'c'.$i);
            $select[] = 'SUM(CASE WHEN '.$filter.' THEN 1 ELSE 0 END) AS c'.$i;
            $rsm->addScalarResult('c'.$i.'_male', 'c'.$i.'_male');
            $select[] = 'SUM(CASE WHEN '.$filter.' AND (u.title=\'M\' OR u.title IS NULL) THEN 1 ELSE 0 END) AS c'.$i.'_male';
            $rsm->addScalarResult('c'.$i.'_female', 'c'.$i.'_female');
            $select[] = 'SUM(CASE WHEN '.$filter.' AND u.title=\'Me\' THEN 1 ELSE 0 END) AS c'.$i++.'_female';
        }

        if ($startDate != '' && $endDate != '') {
            $dateRange = "(u.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0' AND u.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0')";
        } elseif ($startDate == '' && $endDate != '') {
            $dateRange = "u.created_at <= '" . $endDateTime->format('Y-m-d') . " 0:0:0'";
        } elseif ($startDate != '' && $endDate == '') {
            $dateRange = "u.created_at >='" . $startDateTime->format('Y-m-d') . " 0:0:0'";
        } else {
            $dateRange = "u.created_at IS NOT NULL";
        }
        $query = $em->createNativeQuery('
			SELECT '.implode(',', $select).' FROM user AS u
			WHERE ' . $dateRange, $rsm);
        return array_values($query->getSingleResult());
    }
1282774
public function getEvents(\DateTime $begin, \DateTime $end, array $options = array())
    {
        $events = array();

        foreach ($this->providers as $provider) {
            $events = array_merge($events, $provider->getEvents($begin, $end, $options));
        }

        return $events;
    }
301352
public function getEmailStats($date, $endDate = null, $aggregatedBy = null)
    {
        $url = $this->getApiEndpoint() . '/v2/email/stats/since-date/' . $date;
        if ($endDate && $aggregatedBy) {
            $url .= '?endDate=' . $endDate . '&aggregatedBy=' . $aggregatedBy;
        }

        $response = $this->setUrl($url)
            ->setVerb('GET')
            ->execute();

        if (isset($response->message)) {
            $this->helper->log('GET EMAIL STATS : ' . $response->message);
        }

        return $response;
    }
474052
private function getReferersCountFromSessionActivities($start, $end)
    {
        return $this->getVisitsFilteredByDateRange($start, $end)
            ->transform(function (VisitorActivity $visit) {
                return [
                    'name' => $visit->hasReferer()
                        ? $visit->referer->domain->name
                        : trans('tracker::generals.undefined'),
                ];
            })
            ->groupBy('name')
            ->transform(function (Collection $items, $key) {
                return [
                    'name'  => $key,
                    'count' => $items->count(),
                ];
            })
            ->sortByDesc('count');
    }
705140
public function getEndTime(bool $asDateTime = true)
    {
        $endTime = \DateTime::createFromFormat(\DateTime::ATOM, $this->endTime);
        if ($asDateTime && $endTime instanceof \DateTime) {
            return $endTime;
        }

        return $this->endTime;
    }
741053
public function scopeFromDecadesAgo(Builder $query, $ago, $endDateTime = null)
    {
        return $this->scopeFromDateTimeRange(DateTime::getDecadesAgo($ago, $endDateTime));
    }
1236836
public function getApprovalData(int $startTime, int $endTime, int $nextSPNum = 0): array
    {
        $json = [
            'starttime' => $startTime,
            'endtime' => $endTime
        ];

        if ($nextSPNum > 0) {
            $json['next_spnum'] = $nextSPNum;
        }

        return $this->httpClient->postJson('corp/getapprovaldata', $json);
    }
1130631
function _date_time_array( $datetime, $parno=FALSE ) {
    $output = array();
    foreach( $datetime as $dateKey => $datePart ) {
      switch ( $dateKey ) {
        case '0': case 'year':   $output['year']  = $datePart; break;
        case '1': case 'month':  $output['month'] = $datePart; break;
        case '2': case 'day':    $output['day']   = $datePart; break;
      }
      if( 3 != $parno ) {
        switch ( $dateKey ) {
          case '0':
          case '1':
          case '2': break;
          case '3': case 'hour': $output['hour']  = $datePart; break;
          case '4': case 'min' : $output['min']   = $datePart; break;
          case '5': case 'sec' : $output['sec']   = $datePart; break;
          case '6': case 'tz'  : $output['tz']    = $datePart; break;
        }
      }
    }
    if( 3 != $parno ) {
      if( !isset( $output['hour'] ))
        $output['hour'] = 0;
      if( !isset( $output['min']  ))
        $output['min'] = 0;
      if( !isset( $output['sec']  ))
        $output['sec'] = 0;
    }
    return $output;
  }
915634
public function getEventsQuery(\DateTime $begin, \DateTime $end, array $options = array())
    {
        return $this->getEventsQueryBuilder($begin, $end, $options)->getQuery();
    }
137544
public function getLockedDocuments($fromDateTime = null , $tillDateTime = null)
    {
        return $this->getDataUpdater()->getLockedDocuments($fromDateTime, $tillDateTime);
    }
1153583
public function oldestDateAdded($duration, string $timezone = null, \DateTime $dateSend = null)
    {
        if (!$timezone) {
            $timezone = date_default_timezone_get();
        }
        if (is_string($timezone)) {
            $timezone = new \DateTimeZone($timezone);
        }
        if ($dateSend) {
            $oldest = clone $dateSend;
            $oldest->setTimezone($timezone);
        } else {
            $oldest = new \DateTime('now', $timezone);
        }
        if (0 !== strpos($duration, 'P')) {
            // Non-rolling interval, go to previous interval segment.
            // Will only work for simple (singular) intervals.
            switch (strtoupper(substr($duration, -1))) {
                case 'Y':
                    $oldest->modify('next year jan 1 midnight');
                    break;
                case 'M':
                    $oldest->modify('first day of next month midnight');
                    break;
                case 'W':
                    $oldest->modify('sunday next week midnight');
                    break;
                case 'D':
                    $oldest->modify('tomorrow midnight');
                    break;
            }
            // Add P so that we can now use standard interval
            $duration = 'P'.$duration;
        }
        try {
            $interval = new \DateInterval($duration);
        } catch (\Exception $e) {
            // Default to monthly if the interval is faulty.
            $interval = new \DateInterval('P1M');
        }
        $oldest->sub($interval);

        return $oldest;
    }
589514
protected function get_unmailed_posts($starttime, $endtime, $now = null) {
        global $CFG, $DB;

        $params = array();
        $params['mailed'] = FORUM_MAILED_PENDING;
        $params['ptimestart'] = $starttime;
        $params['ptimeend'] = $endtime;
        $params['mailnow'] = 1;

        if (!empty($CFG->forum_enabletimedposts)) {
            if (empty($now)) {
                $now = time();
            }
            $selectsql = "AND (p.created >= :ptimestart OR d.timestart >= :pptimestart)";
            $params['pptimestart'] = $starttime;
            $timedsql = "AND (d.timestart < :dtimestart AND (d.timeend = 0 OR d.timeend > :dtimeend))";
            $params['dtimestart'] = $now;
            $params['dtimeend'] = $now;
        } else {
            $timedsql = "";
            $selectsql = "AND p.created >= :ptimestart";
        }

        return $DB->get_records_sql(
               "SELECT
                    p.id,
                    p.discussion,
                    d.forum,
                    d.course,
                    p.created,
                    p.parent,
                    p.userid
                  FROM {forum_posts} p
                  JOIN {forum_discussions} d ON d.id = p.discussion
                 WHERE p.mailed = :mailed
                $selectsql
                   AND (p.created < :ptimeend OR p.mailnow = :mailnow)
                $timedsql
                 ORDER BY p.modified ASC",
             $params);
    }