DateTime PHP Class Code Examples

This page contains top rated real world PHP examples of class DateTime extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: RangeValidator.php Project: Ener-Getick/symfony
0
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof Range) {
         throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Range');
     }
     if (null === $value) {
         return;
     }
     if (!is_numeric($value) && !$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
         $this->context->buildViolation($constraint->invalidMessage)->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))->setCode(Range::INVALID_CHARACTERS_ERROR)->addViolation();
         return;
     }
     $min = $constraint->min;
     $max = $constraint->max;
     // Convert strings to DateTimes if comparing another DateTime
     // This allows to compare with any date/time value supported by
     // the DateTime constructor:
     // http://php.net/manual/en/datetime.formats.php
     if ($value instanceof \DateTime || $value instanceof \DateTimeInterface) {
         if (is_string($min)) {
             $min = new \DateTime($min);
         }
         if (is_string($max)) {
             $max = new \DateTime($max);
         }
     }
     if (null !== $constraint->max && $value > $max) {
         $this->context->buildViolation($constraint->maxMessage)->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))->setParameter('{{ limit }}', $this->formatValue($max, self::PRETTY_DATE))->setCode(Range::TOO_HIGH_ERROR)->addViolation();
         return;
     }
     if (null !== $constraint->min && $value < $min) {
         $this->context->buildViolation($constraint->minMessage)->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))->setParameter('{{ limit }}', $this->formatValue($min, self::PRETTY_DATE))->setCode(Range::TOO_LOW_ERROR)->addViolation();
     }
 }
Example #2
Show file File: Core.php Project: hoque92/hoquezilla
0
/**
 * Converts an input to a DateTime instance.
 *
 * <pre>
 *    {% if date(user.created_at) < date('+2days') %}
 *      {# do something #}
 *    {% endif %}
 * </pre>
 *
 * @param Twig_Environment                       $env      A Twig_Environment instance
 * @param DateTime|DateTimeInterface|string|null $date     A date
 * @param DateTimeZone|string|null|false         $timezone The target timezone, null to use the default, false to leave unchanged
 *
 * @return DateTime A DateTime instance
 */
function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null)
{
    // determine the timezone
    if (false !== $timezone) {
        if (null === $timezone) {
            $timezone = $env->getExtension('core')->getTimezone();
        } elseif (!$timezone instanceof DateTimeZone) {
            $timezone = new DateTimeZone($timezone);
        }
    }
    // immutable dates
    if ($date instanceof DateTimeImmutable) {
        return false !== $timezone ? $date->setTimezone($timezone) : $date;
    }
    if ($date instanceof DateTime || $date instanceof DateTimeInterface) {
        $date = clone $date;
        if (false !== $timezone) {
            $date->setTimezone($timezone);
        }
        return $date;
    }
    if (null === $date || 'now' === $date) {
        return new DateTime($date, false !== $timezone ? $timezone : $env->getExtension('core')->getTimezone());
    }
    $asString = (string) $date;
    if (ctype_digit($asString) || !empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1))) {
        $date = new DateTime('@' . $date);
    } else {
        $date = new DateTime($date, $env->getExtension('core')->getTimezone());
    }
    if (false !== $timezone) {
        $date->setTimezone($timezone);
    }
    return $date;
}
Example #3
Show file File: Logs.php Project: mheydt/scalr
0
 public function xListApiLogsAction()
 {
     $this->request->restrictAccess(Acl::RESOURCE_LOGS_API_LOGS);
     $this->request->defineParams(['sort' => ['type' => 'json', 'default' => ['property' => 'id', 'direction' => 'DESC']]]);
     $sql = "SELECT * from api_log WHERE env_id = ?";
     $args = [$this->getEnvironmentId()];
     if ($this->getParam('byDate')) {
         try {
             $tz = $this->user->getSetting(Scalr_Account_User::SETTING_UI_TIMEZONE);
             if (!$tz) {
                 $tz = 'UTC';
             }
             $tz = new DateTimeZone($tz);
             $dtS = new DateTime($this->getParam('byDate'), $tz);
             $dtE = new DateTime($this->getParam('byDate'), $tz);
             if ($this->getParam('fromTime')) {
                 $dtS = $dtS->createFromFormat('Y-m-d H:i', $this->getParam('byDate') . ' ' . $this->getParam('fromTime'), $tz);
             }
             if ($this->getParam('toTime')) {
                 $dtE = $dtE->createFromFormat('Y-m-d H:i', $this->getParam('byDate') . ' ' . $this->getParam('toTime'), $tz);
             } else {
                 $dtE = $dtE->add(new DateInterval('P1D'));
             }
             $sql .= ' AND dtadded > ? AND dtadded < ?';
             $args[] = $dtS->getTimestamp();
             $args[] = $dtE->getTimestamp();
         } catch (Exception $e) {
         }
     }
     $response = $this->buildResponseFromSql($sql, ['id', 'dtadded', 'action', 'ipaddress'], ['transaction_id'], $args);
     foreach ($response["data"] as &$row) {
         $row["dtadded"] = Scalr_Util_DateTime::convertTz((int) $row["dtadded"]);
     }
     $this->response->data($response);
 }
Example #4
Show file File: lib.php Project: avillarroelp/bookingrooms
0
function hour_module($module)
{
    global $DB, $USER;
    //in format HH:MM:SS (varchar)
    //Define lthe hours for misreservas.php
    $modules = $DB->get_record('bookingrooms_modules', array("id" => $module));
    $start = explode(":", $modules->hour_start);
    $end = explode(":", $modules->hour_end);
    $a = $start[0];
    $b = $start[1];
    $c = 00;
    //hour;minute;second
    $d = $end[0];
    $e = (int) $end[1];
    $f = 00;
    //hour;minute;second
    $minutes = str_replace(' ', '', $e);
    $ModuleStart = new DateTime();
    // Is left hour and minutes in 0 (midnigth)
    $ModuleStart->setTime($a, $b, 0);
    $ModuleEnd = new DateTime();
    // Is left hour and minutes in 0 (midnigth)
    $ModuleEnd->setTime($d, $e, 0);
    $hour = array($ModuleStart, $ModuloEnd);
    //var_dump($hour);
    return $hour;
    //returns $hour[start] y $hour[end]
}
Example #5
Show file File: SystemCalendarProviderTest.php Project: Maksold/platform
0
 public function testGetCalendarEvents()
 {
     $organizationId = 1;
     $userId = 123;
     $calendarId = 10;
     $start = new \DateTime();
     $end = new \DateTime();
     $connections = [10 => true, 20 => false];
     $events = [['id' => 1]];
     $this->calendarConfig->expects($this->once())->method('isSystemCalendarEnabled')->will($this->returnValue(true));
     $this->securityFacade->expects($this->once())->method('isGranted')->with('oro_system_calendar_view')->will($this->returnValue(true));
     $qb = $this->getMockBuilder('Doctrine\\ORM\\QueryBuilder')->disableOriginalConstructor()->getMock();
     $repo = $this->getMockBuilder('Oro\\Bundle\\CalendarBundle\\Entity\\Repository\\CalendarEventRepository')->disableOriginalConstructor()->getMock();
     $this->doctrineHelper->expects($this->once())->method('getEntityRepository')->with('OroCalendarBundle:CalendarEvent')->will($this->returnValue($repo));
     $repo->expects($this->once())->method('getSystemEventListByTimeIntervalQueryBuilder')->with($this->identicalTo($start), $this->identicalTo($end))->will($this->returnValue($qb));
     $query = $this->getMockBuilder('Doctrine\\ORM\\AbstractQuery')->disableOriginalConstructor()->getMockForAbstractClass();
     $qb->expects($this->at(0))->method('andWhere')->with('c.organization = :organizationId')->will($this->returnSelf());
     $qb->expects($this->at(1))->method('setParameter')->with('organizationId', $organizationId)->will($this->returnSelf());
     $qb->expects($this->at(2))->method('andWhere')->with('c.id NOT IN (:invisibleIds)')->will($this->returnSelf());
     $qb->expects($this->at(3))->method('setParameter')->with('invisibleIds', [20])->will($this->returnSelf());
     $qb->expects($this->once())->method('getQuery')->will($this->returnValue($query));
     $this->calendarEventNormalizer->expects($this->once())->method('getCalendarEvents')->with($calendarId, $this->identicalTo($query))->will($this->returnValue($events));
     $result = $this->provider->getCalendarEvents($organizationId, $userId, $calendarId, $start, $end, $connections);
     $this->assertEquals($events, $result);
 }
Example #6
Show file File: testf.php Project: anisinfo/osi
0
function nbJ_parNom($date1, $date2, $jours, $nomJour, $typej)
{
    //nombre d'une journée de la semaine dans un intervalle de temps:
    // exemple nombre de lundi du 01 au 20 fevrier (sans compter le 01 et le dernier jour de lintervalle)
    // $jours = array('lundi' => 1, 'mardi' => 2, 'mercredi' => 3, 'jeudi' => 4, 'vendredi' => 5, 'samedi' => 6, 'dimanche' => 7);
    $feries = list_joursFeries($date1, $date2);
    $no = 0;
    $start = new DateTime(date('Y-m-d', strtotime($date1 . ' + 1 DAY')));
    $end = new DateTime($date2);
    $interval = DateInterval::createFromDateString('1 day');
    $period = new DatePeriod($start, $interval, $end);
    foreach ($period as $dt) {
        if ($typej === 'f') {
            #jours feries
            if (in_array($dt->format('Y-m-d'), $feries)) {
                $no++;
            }
        } else {
            if ($nomJour) {
                if ($dt->format('N') == $jours[$nomJour] && !in_array($dt->format('Y-m-d'), $feries)) {
                    // echo $dt->format('N D d-m-Y'), "<br>";
                    $no++;
                }
            } else {
                //tous (sauf les feriés)
                $no++;
            }
        }
    }
    return $no;
}
Example #7
Show file File: TimePeriodsUpdateCommand.php Project: dstansby/camdram
0
 protected function addVacation($name, \DateTime $start, \DateTime $end, OutputInterface $output)
 {
     $start_year = $start->format('Y');
     $end_year = $end->format('Y');
     $year = $start_year == $end_year ? $start_year : $start_year . '/' . $end_year;
     $this->createPeriod($name . ' Vacation', $name . ' Vacation', $name . ' Vacation ' . $year, $start, $end, $output);
 }
Example #8
Show file File: Core.php Project: artz20/Tv-shows-zone
0
/**
 * Converts an input to a DateTime instance.
 *
 * <pre>
 *    {% if date(user.created_at) < date('+2days') %}
 *      {# do something #}
 *    {% endif %}
 * </pre>
 *
 * @param Twig_Environment    $env      A Twig_Environment instance
 * @param DateTime|string     $date     A date
 * @param DateTimeZone|string $timezone A timezone
 *
 * @return DateTime A DateTime instance
 */
function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null)
{
    if (!$date instanceof DateTime) {
        $asString = (string) $date;
        if (ctype_digit($asString) || !empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1))) {
            $date = new DateTime('@' . $date);
        } else {
            $date = new DateTime($date);
        }
    } else {
        $date = clone $date;
    }
    // set Timezone
    if (null !== $timezone) {
        if ($timezone instanceof DateTimeZone) {
            $date->setTimezone($timezone);
        } else {
            $date->setTimezone(new DateTimeZone($timezone));
        }
    } elseif (($timezone = $env->getExtension('core')->getTimezone()) instanceof DateTimeZone) {
        $date->setTimezone($timezone);
    } else {
        $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
    }
    return $date;
}
Example #9
Show file File: EntityTest.php Project: mgugniewicz/dodajurlop
0
 public function testSetGetDanych()
 {
     $date = new \DateTime('2015-11-14');
     $this->entity->setKomentarz('kom');
     $this->entity->setDel(true);
     $this->entity->setDodata($date);
     $this->entity->setLicznik(1);
     $this->entity->setModata($date);
     $this->entity->setOpis('normalny opis');
     $this->entity->setWysw(true);
     $this->assertEquals('kom', $this->entity->getKomentarz());
     $this->assertTrue($this->entity->isDel());
     $this->assertEquals($date, $this->entity->getDodata());
     $this->assertEquals(1, $this->entity->getLicznik());
     $this->assertEquals($date, $this->entity->getModata());
     $this->assertEquals('normalny opis', $this->entity->getOpis());
     $this->assertTrue($this->entity->isWysw());
     $date_new = new \DateTime('2014-11-14');
     $this->assertNotEquals('komqwe', $this->entity->getKomentarz());
     $this->assertNotEquals($date_new, $this->entity->getDodata());
     $this->assertNotEquals(12, $this->entity->getLicznik());
     $this->assertNotEquals($date_new, $this->entity->getModata());
     $this->assertNotEquals('normalny opisasdf', $this->entity->getOpis());
     $this->assertNull($this->entity->getId());
 }
Example #10
Show file File: chart.php Project: omusico/suitecrm-docker
0
 public function time_range($start_date, $end_date)
 {
     $datetime1 = new DateTime($start_date);
     $datetime2 = new DateTime($end_date);
     $interval = $datetime1->diff($datetime2);
     echo $interval->format('%y years %m months and %d days');
 }
Example #11
Show file File: TimePeriodTest.php Project: pombredanne/tuleap
0
 public function __construct()
 {
     $week_day = new DateTime('2016-02-01');
     $this->day_timestamp = $week_day->getTimestamp();
     $following_day = new DateTime('2016-02-02');
     $this->following_day_timestamp = $following_day->getTimestamp();
 }
Example #12
Show file File: garbage_collector.php Project: ressphere/cb_iloveproperty
0
 public function deactivate_expired_listing()
 {
     $this->load->model('properties_listing_model');
     $this->load->model('users_model');
     $activated_lists = $this->properties_listing_model->find_all(array('activate' => 1));
     if (!empty($activated_lists)) {
         foreach ($activated_lists as $activated_list) {
             # last query here
             $current_date = new DateTime();
             $activate_date = new DateTime($activated_list->activate_time);
             $diff = date_diff($activate_date, $current_date, TRUE);
             $total_diff = $diff->format('%y') * 12 + $diff->format('%m');
             $expire_duration = $activated_list->deactivate_duration;
             if ((int) $total_diff >= $expire_duration) {
                 $activated_list->activate = 0;
                 $activated_list->save();
                 $user = $this->users_model->find_one(array('id' => $activated_list->user_id));
                 echo $activated_list->ref_tag . " is deactivated \n";
                 $data['ref_tag'] = $activated_list->ref_tag;
                 $this->_send_email('deactivation', $user['email'], $data);
                 echo "Notification sent to " . $user['email'];
             }
         }
     }
 }
Example #13
Show file File: Api.php Project: acmadi/laravel-api
0
 /**
  * Check client request limit and update.
  *
  * @return boolean
  */
 public function checkRequestLimit()
 {
     $isLimitReached = false;
     $client = $this->getClient();
     if (!is_null($client)) {
         $currentTotalRequest = 1;
         $currentTime = time();
         $requestLimitUntil = $currentTime;
         $requestLimitUntil = strtotime($client->request_limit_until);
         if ($requestLimitUntil < 0) {
             $requestLimitUntil = $currentTime;
         }
         if ($currentTime <= $requestLimitUntil) {
             $currentTotalRequest = $client->current_total_request + 1;
             if ($currentTotalRequest > $client->request_limit) {
                 $isLimitReached = true;
             }
         }
         if ($currentTime > $requestLimitUntil) {
             $dateTime = new DateTime('+1 hour');
             $requestLimitUntil = $dateTime->getTimestamp();
             unset($dateTime);
         }
         if (!$isLimitReached) {
             $dateTime = new DateTime();
             $client->current_total_request = $currentTotalRequest;
             $client->request_limit_until = $dateTime->setTimestamp($requestLimitUntil)->format('Y-m-d H:i:s');
             $client->last_request_at = $dateTime->setTimestamp($currentTime)->format('Y-m-d H:i:s');
             $client->save();
             unset($dateTime);
         }
     }
     unset($client);
     return $isLimitReached;
 }
Example #14
Show file File: class.json-api-endpoints.php Project: StefanBonilla/CoupSoup
0
 /**
  * Parses a date string and returns the local and GMT representations
  * of that date & time in 'YYYY-MM-DD HH:MM:SS' format without
  * timezones or offsets. If the parsed datetime was not localized to a
  * particular timezone or offset we will assume it was given in GMT
  * relative to now and will convert it to local time using either the
  * timezone set in the options table for the blog or the GMT offset.
  *
  * @param datetime string
  *
  * @return array( $local_time_string, $gmt_time_string )
  */
 function parse_date($date_string)
 {
     $date_string_info = date_parse($date_string);
     if (is_array($date_string_info) && 0 === $date_string_info['error_count']) {
         // Check if it's already localized. Can't just check is_localtime because date_parse('oppossum') returns true; WTF, PHP.
         if (isset($date_string_info['zone']) && true === $date_string_info['is_localtime']) {
             $dt_local = clone $dt_utc = new DateTime($date_string);
             $dt_utc->setTimezone(new DateTimeZone('UTC'));
             return array((string) $dt_local->format('Y-m-d H:i:s'), (string) $dt_utc->format('Y-m-d H:i:s'));
         }
         // It's parseable but no TZ info so assume UTC
         $dt_local = clone $dt_utc = new DateTime($date_string, new DateTimeZone('UTC'));
     } else {
         // Could not parse time, use now in UTC
         $dt_local = clone $dt_utc = new DateTime('now', new DateTimeZone('UTC'));
     }
     // First try to use timezone as it's daylight savings aware.
     $timezone_string = get_option('timezone_string');
     if ($timezone_string) {
         $tz = timezone_open($timezone_string);
         if ($tz) {
             $dt_local->setTimezone($tz);
             return array((string) $dt_local->format('Y-m-d H:i:s'), (string) $dt_utc->format('Y-m-d H:i:s'));
         }
     }
     // Fallback to GMT offset (in hours)
     // NOTE: TZ of $dt_local is still UTC, we simply modified the timestamp with an offset.
     $gmt_offset_seconds = intval(get_option('gmt_offset') * 3600);
     $dt_local->modify("+{$gmt_offset_seconds} seconds");
     return array((string) $dt_local->format('Y-m-d H:i:s'), (string) $dt_utc->format('Y-m-d H:i:s'));
 }
Example #15
Show file File: auth_model.php Project: phpsong/CI_AuthLTE
0
 /**
  * Verify that the provided password reset token is correct.
  * Use this function if you are using the send_reset_password_email() fumction
  * before calling the reset_password() function.
  * 
  * @param string $email
  * @param string $token
  * 
  * @return boolean
  */
 public function verify_password_reset_tk($email, $token)
 {
     $this->db->select('reset_password_tk, reset_password_tk_date');
     $this->db->where('email', $email);
     $query = $this->db->get('accounts');
     if ($query->num_rows() != 1) {
         //email does not exist
         return FALSE;
     }
     //fetch row
     $row = $query->row();
     //chack if email expired
     if (empty($row->reset_password_tk)) {
         //Token does not exist
         return FALSE;
     }
     $now = new DateTime('now');
     $tk_date = new DateTime($row->reset_password_tk_date);
     $tk_date->modify("+{$this->settings['password_reset_date_limit']} SECONDS");
     if ($tk_date >= $now) {
         //Token has expired
         return FALSE;
     }
     $this->load->library('phpass');
     if (!$this->phpass->check($token, $row->reset_password_tk)) {
         //Token does not match
         return FALSE;
     }
     return TRUE;
 }
Example #16
Show file File: Abstract.php Project: unifiedarts/Hackathon_MageMonitoring
0
 /**
  * Returns log entries with timestamp after $from or false if $from is not found.
  *
  * @param  string $log  Log
  * @param  string $from From
  * @return string|false
  */
 protected function extractNewLogEntries($log, $from)
 {
     $regOut = array();
     // find last time stamp
     $pattern = '/(' . $this->_regexLogstamp . ')(?!.*' . $this->_regexLogstamp . ')(.+)\\z/ms';
     if (preg_match_all($pattern, $log, $regOut)) {
         // last time stamp in log
         $curExcept = $regOut[1][0];
         $curExceptDate = new DateTime($curExcept);
         $lastSavedDate = null;
         if ($from) {
             $lastSavedDate = new DateTime($from);
         }
         if ($from == null || $lastSavedDate != $curExceptDate) {
             $this->saveConfig(array(self::CONFIG_LAST_LOG_ENTRY => array('value' => $curExcept)), true);
             // try to match everything after last logged exception
             $r = array();
             $p = '/(!?' . str_replace('+', '\\+', $from) . ').*((' . $this->_regexLogstamp . ')(.*?))\\z/ms';
             $logOutput = '';
             if ($from && preg_match_all($p, $log, $r)) {
                 return $r[7][0];
             }
         }
     }
     return false;
 }
Example #17
Show file File: functions_calendar.php Project: dsyman2/integriaims
0
function calendar_get_non_working_days($year = false)
{
    global $config;
    $holidays = get_db_all_rows_in_table("tholidays", "day");
    if (!$year || $config["working_weekends"]) {
        return $holidays;
    }
    $res = array();
    foreach ($holidays as $holiday) {
        $day = new DateTime($holiday["day"]);
        $res[] = $day->format("Y-m-d");
    }
    $start = new DateTime("{$year}-1-1");
    $end = new DateTime("{$year}-12-31");
    $endTimestamp = $end->getTimestamp();
    if ($start->format("w") == 6 || $start->format("w") == 0) {
        $d = $start;
    } else {
        $d = $start->modify("next saturday");
    }
    $oneday = new DateInterval("P1D");
    $sixdays = new DateInterval("P6D");
    while ($d->getTimestamp() <= $endTimestamp) {
        $res[] = $d->format("Y-m-d");
        $d = $d->add($oneday);
        if ($d->getTimestamp() <= $endTimestamp) {
            $res[] = $d->format("Y-m-d");
        }
        $d = $d->add($sixdays);
    }
    return $res;
}
Example #18
Show file File: iCalcreator.class.php Project: cjvaz/expressomail
0
 /**
  * transforms a dateTime from a timezone to another using PHP DateTime and DateTimeZone class (PHP >= PHP 5.2.0)
  *
  * @author Kjell-Inge Gustafsson, kigkonsult <ical@kigkonsult.se>
  * @since 2.15.1 - 2012-10-17
  * @param mixed  $date,   date to alter
  * @param string $tzFrom, PHP valid 'from' timezone
  * @param string $tzTo,   PHP valid 'to' timezone, default 'UTC'
  * @param string $format, date output format, default 'Ymd\THis'
  * @return bool
  */
 public static function transformDateTime(&$date, $tzFrom, $tzTo = 'UTC', $format = 'Ymd\\THis')
 {
     if (is_array($date) && isset($date['timestamp'])) {
         try {
             $d = new DateTime("@{$date['timestamp']}");
             // set UTC date
             $d->setTimezone(new DateTimeZone($tzFrom));
             // convert to 'from' date
         } catch (Exception $e) {
             return FALSE;
         }
     } else {
         if (iCalUtilityFunctions::_isArrayDate($date)) {
             if (isset($date['tz'])) {
                 unset($date['tz']);
             }
             $date = iCalUtilityFunctions::_date2strdate(iCalUtilityFunctions::_chkDateArr($date));
         }
         if ('Z' == substr($date, -1)) {
             $date = substr($date, 0, strlen($date) - 2);
         }
         try {
             $d = new DateTime($date, new DateTimeZone($tzFrom));
         } catch (Exception $e) {
             return FALSE;
         }
     }
     try {
         $d->setTimezone(new DateTimeZone($tzTo));
     } catch (Exception $e) {
         return FALSE;
     }
     $date = $d->format($format);
     return TRUE;
 }
Example #19
Show file File: gpswriter.class.php Project: vivek779/gpsmap
0
 /**
  * Store the GPS point in the database
  *
  * @param string  $deviceid  Pass in an ID that matches the deviceid in the Settings class
  * @param integer $trackId   A unique id identifying the point belongs to a certain track
  * @param integer $timestamp Timestamp of the GPS point in milliseconds
  * @param float   $latitude  GPS Point latitude (points to the South should be negative)
  * @param float   $longitude GPS Point longitude (points to the West should be negative)
  * @param integer $altitude  Altitude of the GPS point in meters
  *
  * @access public
  * @return boolean false if device ID does not match Settings
  */
 public function storePoint($device, $trackId, $timestamp, $latitude, $longitude, $altitude)
 {
     if ($device !== Settings::DEVICEID) {
         return false;
     }
     $theDate = new DateTime(urldecode($timestamp), new DateTimeZone(Settings::TIMEZONE));
     error_log("The date is " . $theDate->format('Y-m-d H:i:s'));
     try {
         $lastPoint = $this->location->getLatestLocation($theDate->format('Y-m-d H:i:s'));
         if ($lastPoint !== false) {
             $newDistance = Utilities::haversine($lastPoint['lat'], $lastPoint['lng'], $latitude, $longitude);
             $distance = $lastPoint['distance'] + $newDistance * Settings::KM_TO_MILES;
             $previousDataTime = new DateTime($lastPoint['datatime'], new DateTimeZone(Settings::TIMEZONE));
             $interval = $theDate->diff($previousDataTime);
             $secondsPassed = $interval->format('%s');
             $speedMPS = $newDistance * 1000 / $secondsPassed;
             $speed = $speedMPS * Settings::MPS_TO_MPH;
             $heading = Utilities::getRhumbLineBearing($lastPoint['lat'], $lastPoint['lng'], $latitude, $longitude);
         } else {
             $speed = 0;
             $heading = 0;
             $distance = 0;
         }
         $insert = "REPLACE INTO gpsdata (devicekey, tracktag, coord, altitude, datatime, speed, heading, distance)\n                VALUES\n                (:device, :trackid, GeomFromText('POINT({$latitude} {$longitude})'), :altitude, :datatime, :speed, :heading, :distance)";
         $stmt = $this->dbConn->prepare($insert);
         $stmt->execute(array(':device' => $device, ':trackid' => $trackId, ':altitude' => $altitude, ':datatime' => $theDate->format('Y-m-d H:i:s'), ':speed' => $speed, ':heading' => $heading, ':distance' => $distance));
     } catch (Exception $e) {
         error_log($e->getMessage());
     }
 }
Example #20
Show file File: Summary_model.php Project: EMSL-MSC/pacifica-reporting
0
 /**
  *  Backend database function to aggregate data over several
  *  different types of object groupings.
  *
  *  @param array   $id_list        list of object id's
  *  @param string  $start_date     starting date (YYYY-MM-DD)
  *  @param string  $end_date       ending date (YYYY-MM-DD)
  *  @param boolean $make_day_graph toggle to control whether or not
  *                                 per day totals are included
  *  @param string  $time_basis     one of created_date, modified_date,
  *                                 submitted_date
  *  @param string  $group_type     type of group to summarize over
  *
  *  @return array
  *
  *  @author Ken Auberry <kenneth.auberry@pnnl.gov>
  */
 public function summarize_uploads_general($id_list, $start_date, $end_date, $make_day_graph, $time_basis, $group_type)
 {
     extract($this->canonicalize_date_range($start_date, $end_date));
     $start_date_obj = new DateTime($start_date);
     $end_date_obj = new DateTime($end_date);
     $available_dates = $this->_generate_available_dates($start_date_obj, $end_date_obj);
     if ($group_type == 'instrument' || $group_type == 'proposal') {
         $group_list_retrieval_fn_name = "get_{$group_type}_group_list";
         $group_collection = array();
         foreach ($id_list as $item_id) {
             $new_collection = $this->gm->{$group_list_retrieval_fn_name}($item_id);
             $group_collection = $group_collection + $new_collection;
         }
         $group_list = array_keys($group_collection);
         if (empty($group_list)) {
             // no results returned for group list => bail out
         }
         $temp_totals = $this->_get_summary_totals_from_group_list($group_list, $start_date_obj, $end_date_obj, $time_basis, $group_type);
         $temp_results = $this->_get_per_day_totals_from_group_list($group_list, $start_date_obj, $end_date_obj, $time_basis, $group_type);
     } else {
         if ($group_type == 'user') {
             $temp_totals = $this->_get_summary_totals_from_user_list($id_list, $start_date_obj, $end_date_obj, $time_basis);
             $temp_results = $this->get_per_day_totals_from_user_list($id_list, $start_date_obj, $end_date_obj, $time_basis);
         }
     }
     $this->results['day_graph']['by_date']['available_dates'] = $available_dates;
     $this->results['day_graph']['by_date'] = $this->_temp_stats_to_output($temp_results['aggregate'], $available_dates);
     $this->results['summary_totals'] = $temp_results['totals'];
     $this->results['summary_totals']['upload_stats'] = $temp_totals['results'];
     return $this->results;
 }
Example #21
Show file File: lottery.php Project: saqar/FusionCMS-themes-and-modules
0
 private function _expiresInFormatted($end_date)
 {
     $first_date = new DateTime(date('Y-m-d H:i:s', strtotime($end_date)));
     $second_date = new DateTime(date('Y-m-d H:i:s'));
     $difference = $second_date->diff($first_date);
     return $this->_formatInterval($difference);
 }
Example #22
Show file File: TransactionRepository.php Project: thomasage/asso
0
 /**
  * @param \DateTime $start
  * @param \DateTime $stop
  * @return array
  */
 public function statAccountSummary(\DateTime $start, \DateTime $stop)
 {
     // Total before season selected
     //
     $previous = (double) $this->createQueryBuilder('t')->select('SUM( t.amount ) amount')->andWhere('t.date < :date')->setParameter('date', $start)->getQuery()->getSingleScalarResult();
     // Total for season selected
     $period = (double) $this->createQueryBuilder('t')->select('SUM( t.amount ) amount')->andWhere('t.date BETWEEN :start AND :stop')->setParameter('start', $start)->setParameter('stop', $stop)->getQuery()->getSingleScalarResult();
     // Expenses for season selected
     $query = 'SELECT d.category AS category,
                      SUM( d.amount ) AS amount
               FROM transaction AS t 
               LEFT JOIN transaction_detail AS d ON t.id = d.transaction_id
               WHERE d.amount < 0
               AND   t.date BETWEEN :start AND :stop
               GROUP BY d.category
               ORDER BY d.category ASC';
     $rsm = new ResultSetMapping();
     $rsm->addScalarResult('category', 'category')->addScalarResult('amount', 'amount');
     $expenses = $this->_em->createNativeQuery($query, $rsm)->setParameter('start', $start)->setParameter('stop', $stop)->getArrayResult();
     // Receipts for season selected
     $query = 'SELECT d.category AS category,
                      SUM( d.amount ) AS amount
               FROM transaction AS t 
               LEFT JOIN transaction_detail AS d ON t.id = d.transaction_id
               WHERE d.amount > 0
               AND   t.date BETWEEN :start AND :stop
               GROUP BY d.category
               ORDER BY d.category ASC';
     $rsm = new ResultSetMapping();
     $rsm->addScalarResult('category', 'category')->addScalarResult('amount', 'amount');
     $receipts = $this->_em->createNativeQuery($query, $rsm)->setParameter('start', $start)->setParameter('stop', $stop)->getArrayResult();
     return ['expenses' => $expenses, 'receipts' => $receipts, 'previous' => ['stop' => new \DateTime(date('Y-m-d', strtotime('-1 day', $start->getTimestamp()))), 'amount' => $previous], 'period' => ['stop' => $stop, 'amount' => $period]];
 }
Example #23
Show file File: DateTimeHelper.php Project: SylvainSimon/Metinify
0
 public static function minutesToString($minutes = "")
 {
     $dtF = new DateTime("@0");
     $dtT = new DateTime("@0");
     $dtT->add(new DateInterval('PT' . $minutes . 'M'));
     return $dtF->diff($dtT)->format('%a jour, %h heures, %i minutes');
 }
Example #24
Show file File: CrawlerListingSearch.php Project: Waldz/HomeAwayCrawler
0
 /**
  * @param Listing $listing
  * @param string $type
  * @param string $basis
  * @param \DateTime $dateStart
  * @param \DateTime $dateEnd
  * @param string $currency
  * @param \simple_html_dom_node|array $priceDom
  * @param \simple_html_dom_node|array $priceNotes
  *
  * @throws \UnexpectedValueException
  */
 protected function parsePriceByType(Listing $listing, $type, $basis, \DateTime $dateStart, \DateTime $dateEnd, $currency, $priceDom, $priceNotes)
 {
     if (!isset($priceDom)) {
         return;
     }
     $price = '';
     foreach ($priceDom->nodes as $node) {
         if ($node->tag == 'text') {
             $price .= trim($node->text());
         }
     }
     if (empty($price)) {
         return;
     }
     $price = str_replace(array('$', ','), '', trim($price));
     if (!is_numeric($price)) {
         throw new \UnexpectedValueException(sprintf('Price ammount not found in "%s"', trim($priceDom->text())));
     }
     $priceNotes = trim($priceNotes->text());
     $listingPrice = $listing->getPrice($type, $dateStart, $dateEnd);
     if (!isset($listingPrice)) {
         $listingPrice = new ListingPrice();
         $listing->addPrice($listingPrice);
     }
     $listingPrice->setType($type)->setBasis($basis)->setDateStart($dateStart)->setDateEnd($dateEnd)->setPrice($price)->setCurrency($currency)->setNotes($priceNotes);
 }
Example #25
Show file File: requests.php Project: shawnyeh/jorani
0
 /**
  * Send a leave request email to the employee that requested the leave
  * The method will check if the leave request was accepted or rejected 
  * before sending the e-mail
  * @param int $id Leave request identifier
  * @author Benjamin BALET <benjamin.balet@gmail.com>
  */
 private function sendMail($id)
 {
     $this->load->model('users_model');
     $this->load->model('organization_model');
     $leave = $this->leaves_model->getLeaves($id);
     $employee = $this->users_model->getUsers($leave['employee']);
     $supervisor = $this->organization_model->getSupervisor($employee['organization']);
     //Send an e-mail to the employee
     $this->load->library('email');
     $this->load->library('polyglot');
     $usr_lang = $this->polyglot->code2language($employee['language']);
     //We need to instance an different object as the languages of connected user may differ from the UI lang
     $lang_mail = new CI_Lang();
     $lang_mail->load('email', $usr_lang);
     $lang_mail->load('global', $usr_lang);
     $date = new DateTime($leave['startdate']);
     $startdate = $date->format($lang_mail->line('global_date_format'));
     $date = new DateTime($leave['enddate']);
     $enddate = $date->format($lang_mail->line('global_date_format'));
     $this->load->library('parser');
     $data = array('Title' => $lang_mail->line('email_leave_request_validation_title'), 'Firstname' => $employee['firstname'], 'Lastname' => $employee['lastname'], 'StartDate' => $startdate, 'EndDate' => $enddate, 'StartDateType' => $lang_mail->line($leave['startdatetype']), 'EndDateType' => $lang_mail->line($leave['enddatetype']), 'Cause' => $leave['cause'], 'Type' => $leave['type_name']);
     if ($leave['status'] == 3) {
         //accepted
         $message = $this->parser->parse('emails/' . $employee['language'] . '/request_accepted', $data, TRUE);
         $subject = $lang_mail->line('email_leave_request_accept_subject');
     } else {
         //rejected
         $message = $this->parser->parse('emails/' . $employee['language'] . '/request_rejected', $data, TRUE);
         $subject = $lang_mail->line('email_leave_request_reject_subject');
     }
     sendMailByWrapper($this, $subject, $message, $employee['email'], is_null($supervisor) ? NULL : $supervisor->email);
 }
Example #26
Show file File: class-fire-utils.php Project: un1coin/ovn-space
0
 /**
  * Return boolean OR number of days since last update OR PHP version < 5.2
  *
  * @package Customizr
  * @since Customizr 3.2.6
  */
 function tc_post_has_update($_bool = false)
 {
     //php version check for DateTime
     //http://php.net/manual/fr/class.datetime.php
     if (version_compare(PHP_VERSION, '5.2.0') < 0) {
         return false;
     }
     //first proceed to a date check
     $dates_to_check = array('created' => get_the_date('Y-m-d g:i:s'), 'updated' => get_the_modified_date('Y-m-d g:i:s'), 'current' => date('Y-m-d g:i:s'));
     //ALL dates must be valid
     if (1 != array_product(array_map(array($this, 'tc_is_date_valid'), $dates_to_check))) {
         return false;
     }
     //Import variables into the current symbol table
     extract($dates_to_check);
     //Instantiate the different date objects
     $created = new DateTime($created);
     $updated = new DateTime($updated);
     $current = new DateTime($current);
     $created_to_updated = $this->tc_date_diff($created, $updated);
     $updated_to_today = $this->tc_date_diff($updated, $current);
     if (true === $_bool) {
         //return ( 0 == $created_to_updated -> days && 0 == $created_to_updated -> s ) ? false : true;
         return $created_to_updated->s > 0 || $created_to_updated->i > 0 ? true : false;
     } else {
         //return ( 0 == $created_to_updated -> days && 0 == $created_to_updated -> s ) ? false : $updated_to_today -> days;
         return $created_to_updated->s > 0 || $created_to_updated->i > 0 ? $updated_to_today->days : false;
     }
 }