public function testInstanceFromDateTimeKeepsMicros() { $micro = 254687; $datetime = \DateTime::createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.' . $micro); $carbon = Carbon::instance($datetime); $this->assertSame($micro, $carbon->micro); }
/** * Return a timestamp as DateTime object. * * @param mixed $value * @return \Carbon\Carbon */ protected function asDateTime($value) { // \Log::debug('asDateTime: '.$value); // If this value is an integer, we will assume it is a UNIX timestamp's value // and format a Carbon object from this timestamp. This allows flexibility // when defining your date fields as they might be UNIX timestamps here. if (is_numeric($value)) { // \Log::debug('a'); return Carbon::createFromTimestamp($value); } elseif (preg_match('/^(\\d{4})-(\\d{2})-(\\d{2})$/', $value)) { // \Log::debug('b'); return Carbon::createFromFormat('Y-m-d', $value)->startOfDay(); } elseif (preg_match('/^(\\d{2}):(\\d{2})(:(\\d{2}))?$/', $value)) { // \Log::debug('c'); $value = Carbon::createFromFormat('H:i:s', $value); } elseif (!$value instanceof DateTime) { // \Log::debug('d'); if (null === $value) { return $value; } $format = $this->getDateFormat(); return Carbon::createFromFormat($format, $value); } return Carbon::instance($value); }
/** * Return a timestamp as Carbon object. * * A slightly modified version of \Illuminate\Database\Eloquent\Model::asDateTime(). * * @param mixed $value * @param string|null $format * @return Carbon */ protected function __toCarbon($value, $format = null) { // If this value is already a Carbon instance, we shall just return it as is. // This prevents us having to reinstantiate a Carbon instance when we know // it already is one, which wouldn't be fulfilled by the DateTime check. if ($value instanceof Carbon) { return $value; } // If the value is already a DateTime instance, we will just skip the rest of // these checks since they will be a waste of time, and hinder performance // when checking the field. We will just return the DateTime right away. if ($value instanceof DateTime) { return Carbon::instance($value); } // If this value is an integer, we will assume it is a UNIX timestamp's value // and format a Carbon object from this timestamp. This allows flexibility // when defining your date fields as they might be UNIX timestamps here. if (is_numeric($value)) { return Carbon::createFromTimestamp($value); } // If the value is in simply year, month, day format, we will instantiate the // Carbon instances from that format. Again, this provides for simple date // fields on the database, while still supporting Carbonized conversion. if (preg_match('/^(\\d{4})-(\\d{2})-(\\d{2})$/', $value)) { return Carbon::createFromFormat('Y-m-d', $value)->startOfDay(); } // Use the $format if one was given. if (isset($format) && is_string($format)) { return Carbon::createFromFormat($format, $value); } // Finally, we'll let carbon work out the format (watch out for ambiguous days/months). return Carbon::parse($value); }
/** * {@inheritdoc} */ public function convertToPHPValue($value, AbstractPlatform $platform) { if ($value === null) { return $value; } return Carbon::instance(parent::convertToPHPValue($value, $platform)); }
/** * @return Carbon */ public function getDate() { if ($this->date) { return Carbon::instance($this->date); } return null; }
public function dateInfo($day, $month, $year) { $this->day = $day; $this->month = $month; $this->year = $year; $yearnow = date("Y"); $nowday = Carbon::instance(new \DateTime()); if (!$this->validDate()) { $mes = 'An incorrect date format'; return $mes; } $newyear = Carbon::instance(new \DateTime("01.01.{$yearnow}")); $enterdate = Carbon::instance(new \DateTime("{$this->day}.{$this->month}.{$this->year}")); $diffday = $enterdate->day - $nowday->day; $diffmonth = $enterdate->month - $nowday->month; $diffyear = $enterdate->year - $nowday->year; $daystartyear = $nowday->dayOfYear; $monthstartyear = $nowday->month - $newyear->month; $timezons = $nowday->timezoneName; $mes = 'You entered ' . $enterdate->toDateString() . '<br/>'; $mes .= 'Now ' . $nowday->toDateString() . '<br/>'; if ($diffday == 0 && $diffmonth == 0 && $diffyear == 0) { $mes .= 'You enter the current date'; } elseif ($diffday > 0 || $diffmonth > 0 || $diffyear > 0) { $mes .= 'More than the current date entered in the ' . abs($diffday) . ' days and ' . abs($diffmonth) . ' month ' . abs($diffyear) . ' year(s)'; } else { $mes .= 'Less than the current date entered by ' . abs($diffday) . ' days and ' . abs($diffmonth) . ' month ' . abs($diffyear) . ' year(s)'; } $mes .= "<br/> Your time zone: {$timezons}"; $mes .= "<br/> Since the beginning of this year went {$monthstartyear} full months or {$daystartyear} days"; return $mes; }
/** * Create a new CarbonPeriod instance. * * @param \DateTime $startDate * @param \DateTime $endDate */ public function __construct(\DateTime $startDate = null, \DateTime $endDate = null) { $this->startDate = new CarbonDate($startDate); $this->endDate = $endDate ? CarbonDate::instance($endDate) : $this->startDate->copy()->addDay()->startOfDay(); $this->order(); return $this; }
/** * Run the database seeds. * * @return void */ public function run() { $faker = Faker\Factory::create(); // Create a faker, add en_SG providers $faker->addProvider(new Faker\Provider\en_SG\Address($faker)); $faker->addProvider(new Faker\Provider\en_SG\Enhanced($faker)); $faker->addProvider(new Faker\Provider\en_SG\Person($faker)); $faker->addProvider(new Faker\Provider\en_SG\PhoneNumber($faker)); $faker->seed(9876); // Calling the same script twice with the same seed produces the same results $durations = [30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180]; // Insert 30 dummy records foreach (range(1, 30) as $index) { $startDate = $faker->dateTimeBetween('-3 months', '3 months'); $startHour = ['08', '09', '10', '11', '13', '14', '15', '16']; $startMin = ['00', '15', '30', '45']; while (Carbon::instance($startDate)->dayOfWeek === Carbon::SUNDAY) { $startDate = $faker->dateTimeBetween('-3 months', '3 months'); } if ($startDate === Carbon::SATURDAY) { $startHour = ['08', '09', '10', '11']; } $startTime = $faker->randomElement($startHour) . ":" . $faker->randomElement($startMin) . ":00"; $elderly = Elderly::with('centre')->find($faker->numberBetween(1, 15)); $staffList = $elderly->centre->staff->lists('staff_id')->toArray(); Activity::create(['datetime_start' => $startDate->format('Y-m-d') . " " . $startTime, 'expected_duration_minutes' => $faker->randomElement($durations), 'category' => 'transport', 'more_information' => $faker->optional(0.4, '')->sentence(10, true), 'location_from_id' => $elderly->centre_id, 'location_to_id' => $faker->numberBetween(4, 6), 'elderly_id' => $elderly->elderly_id, 'centre_id' => $elderly->centre_id, 'staff_id' => $faker->randomElement($staffList)]); } }
public function testConstructorShouldAcceptDateTimeObject() { $dt = new DateTime("2014-01-09 11:14:15.638276"); $carbon = Carbon::instance($dt); $test = new DateRange($dt); $this->assertEquals($carbon, $test->start); }
/** * @param CreateWorkshop $command * @throws Exception */ public function handle(CreateWorkshop $command) { if (!is_array($command->lessons) || count($command->lessons) === 0) { throw new Exception("Lessons collection can't be empty!"); } $calendar = new Calendar(null, $command->title); $command->calendar = $calendar; $workshop = $this->workshopFactory->createFromCommand($command); /** @var CreateLesson $lessonCommand */ foreach ($command->lessons as $lessonCommand) { $duration = Carbon::instance($lessonCommand->startDate)->diffInMinutes(Carbon::instance($lessonCommand->endDate), true); $eventCommand = new CreateEventCommand(); $eventCommand->calendar = $calendar; $eventCommand->duration = $duration; $eventCommand->startDate = $lessonCommand->startDate; $eventCommand->endDate = Carbon::instance($lessonCommand->startDate)->addMinutes($duration); $eventCommand->repetitionDays = []; $eventCommand->type = EventType::TYPE_SINGLE; $event = $this->eventFactory->createFromCommand($eventCommand); $occurrences = $this->occurrenceFactory->generateCollectionFromEvent($event); $calendar->events()->add($event); if (count($occurrences) == !1) { throw new Exception('Could not generate occurrences from event'); } $event->setOccurrences($occurrences); $lessonCommand->workshop = $workshop; $lessonCommand->event = $event; $lesson = $this->lessonFactory->createFromCommand($lessonCommand); $workshop->addLesson($lesson); } $this->calendarRepository->insert($calendar); $this->workshopRepository->insert($workshop); }
public function convertToPHPValue($value, AbstractPlatform $platform) { $result = parent::convertToPHPValue($value, $platform); if ($result instanceof \DateTime) { return Carbon::instance($result); } return $result; }
/** * Ensure Timestamps are returned in DateTime. * * @param \DateTime $value * * @return \DateTime */ protected function asDateTime($value) { // Legacy support for Laravel 5.0 if (!$value instanceof Carbon) { return Carbon::instance($value); } return parent::asDateTime($value); }
/** * Determine if the entity is on grace period after cancellation. * * @return bool */ public function onGracePeriod() { if (!is_null($endsAt = $this->billing_subscription_ends_at)) { return Carbon::now()->lt(Carbon::instance($endsAt)); } else { return false; } }
public function setUp() { // Setup ExampleModel. $this->reflect(new ExampleModel()); // Setup Carbon instance. $this->dateTime = new DateTime(); $this->carbon = Carbon::instance($this->dateTime); }
public function next_lesson_of($name, $date = false) { $date = $date ? Carbon::instance($date) : Carbon::now(); foreach ($this->lessons()->where('start', '>=', $date->setTime(0, 0, 0)->format("Y-m-d H:i:s"))->where('end', '<=', $date->setTime(23, 59, 59)->format("Y-m-d H:i:s"))->get() as $lesson) { if ($lesson->subject == $name) { return $lesson; } } }
public function getLatestBalance(Account $acc, \DateTime $date = null) { $dt = Carbon::instance($date)->endOfDay(); $builder = $this->createQueryBuilder('ab')->leftJoin('ab.account', 'acc')->where('acc = :account')->addOrderBy('ab.created_at', 'DESC')->setMaxResults(1)->setParameters(['account' => $acc]); if ($date) { $builder->andWhere('ab.created_at <= :end_of_day')->setParameter('end_of_day', $dt); } return $builder->getQuery()->getOneOrNullResult(); }
public static function isConnected($objPlayer = null, $interval = 0) { $dt2 = \Carbon\Carbon::now(); $difference = $dt2->diffInMinutes(\Carbon\Carbon::instance($objPlayer->getLastPlay())); if ($difference > $interval) { return false; } else { return true; } }
/** * Formatea el valor entregado para convertilo en una fecha de tipo "Carbon" * * @param mixed $value * @return array */ public function getCarbonDate($value) { if (gettype($value) == 'string') { return new Carbon($value); } if (gettype($value) == 'object' && get_class($value) == 'DateTime') { return Carbon::instance($value); } return $value; }
/** * Build config type form * * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $app = $this->app; $builder->add('coupon_cd', 'text', array('label' => 'クーポンコード', 'required' => true, 'trim' => true, 'constraints' => array(new Assert\NotBlank(), new Assert\Regex(array('pattern' => '/^[a-zA-Z0-9]+$/i')))))->add('coupon_name', 'text', array('label' => 'クーポン名', 'required' => true, 'trim' => true, 'constraints' => array(new Assert\NotBlank())))->add('coupon_type', 'choice', array('choices' => array(1 => '商品', 2 => 'カテゴリ'), 'required' => true, 'expanded' => true, 'multiple' => false, 'label' => 'クーポン有効対象', 'empty_value' => false, 'constraints' => array(new Assert\NotBlank())))->add('discount_type', 'choice', array('choices' => array(1 => '値引き額', 2 => '値引率'), 'required' => true, 'expanded' => true, 'multiple' => false, 'label' => '値引き種別', 'constraints' => array(new Assert\NotBlank())))->add('discount_price', 'money', array('label' => '値引き額', 'required' => false, 'currency' => 'JPY', 'precision' => 0))->add('discount_rate', 'integer', array('label' => '値引率', 'required' => false, 'constraints' => array(new Assert\Range(array('min' => 1, 'max' => 100)))))->add('available_from_date', 'date', array('label' => '有効期間', 'required' => true, 'input' => 'datetime', 'widget' => 'single_text', 'format' => 'yyyy-MM-dd', 'empty_value' => array('year' => '----', 'month' => '--', 'day' => '--'), 'constraints' => array(new Assert\NotBlank())))->add('available_to_date', 'date', array('label' => '有効期間日(TO)', 'required' => true, 'input' => 'datetime', 'widget' => 'single_text', 'format' => 'yyyy-MM-dd', 'empty_value' => array('year' => '----', 'month' => '--', 'day' => '--'), 'constraints' => array(new Assert\NotBlank())))->add('coupon_use_time', 'integer', array('label' => '発行枚数', 'required' => true, 'constraints' => array(new Assert\NotBlank(), new Assert\Range(array('min' => 1, 'max' => 1000000)))))->add('CouponDetails', 'collection', array('type' => 'admin_coupon_detail', 'allow_add' => true, 'allow_delete' => true, 'prototype' => true))->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use($app) { $form = $event->getForm(); $data = $form->getData(); if (count($data['CouponDetails']) == 0) { $form['coupon_type']->addError(new FormError('クーポン有効対象となる商品情報またはカテゴリ情報を設定してください。')); } if ($data['discount_type'] == 1) { // 値引き額 /** @var ConstraintViolationList $errors */ $errors = $app['validator']->validateValue($data['discount_price'], array(new Assert\NotBlank())); if ($errors->count() > 0) { foreach ($errors as $error) { $form['discount_price']->addError(new FormError($error->getMessage())); } } } else { if ($data['discount_type'] == 2) { // 値引率 /** @var ConstraintViolationList $errors */ $errors = $app['validator']->validateValue($data['discount_rate'], array(new Assert\NotBlank(), new Assert\Range(array('min' => 0, 'max' => 100)))); if ($errors->count() > 0) { foreach ($errors as $error) { $form['discount_rate']->addError(new FormError($error->getMessage())); } } } } if (!empty($data['available_from_date']) && !empty($data['available_to_date'])) { $now = Carbon::today(); $fromDate = Carbon::instance($data['available_from_date']); $toDate = Carbon::instance($data['available_to_date']); if ($fromDate->gt($toDate)) { $form['available_from_date']->addError(new FormError('有効期間に誤りがあります。')); } } // 既に登録されているクーポンコードは利用できない if (null !== $data->getCouponCd()) { $qb = $app['eccube.plugin.coupon.repository.coupon']->createQueryBuilder('c')->select('COUNT(c)')->where('c.coupon_cd = :coupon_cd')->setParameter('coupon_cd', $data->getCouponCd()); // 新規登録時. if ($data->getId() === null) { $count = $qb->getQuery()->getSingleScalarResult(); // 編集時. } else { $qb->andWhere('c.id <> :coupon_id')->setParameter('coupon_id', $data->getId()); $count = $qb->getQuery()->getSingleScalarResult(); } if ($count > 0) { $form['coupon_cd']->addError(new FormError('既に利用されているクーポンコードです。')); } } }); }
public function getEndDateAttribute($value) { //return a Carbon instance so that DatePicker doesn't crash if (!is_null($value)) { $utc = Utils::setUTCTimezone($value); //when coming from DB the date gets stripped of its timezone. So we need to set it back to UTC and then to local timezone $date = Utils::setLocalTimezone($utc); $carbon = Carbon::instance($date)->timezone(Utils::getLocalTimeZone()); return $carbon; } }
public static function toCarbon($date) { if (is_object($date) && $date instanceof Carbon) { $carbon = $date; } elseif (is_object($date) && $date instanceof DateTime) { $carbon = Carbon::instance($date); } else { $carbon = Carbon::parse($date); } return $carbon; }
/** * Calculate the number of minutes with the given duration. * * @param DateTime|int $minutes Either the exact date at which the item expire, or ttl in minutes * * @return int A number of seconds to use in Redis commands * @throws Exception */ public static function getTtlInSeconds($minutes) { if ($minutes instanceof DateTime) { $fromNow = -Carbon::instance($minutes)->diffInSeconds(null, false); if ($fromNow < 0) { throw new Exception("Cache TTL should be >=0"); } return $fromNow; } return $minutes * 60; }
/** * Get the value of the property from the response and convert any DateTime's to Carbon in the proper time zone * * @param mixed $response * @param string $getter * * @return mixed */ private function getPropertyValue($response, $getter) { $value = $response->{$getter}(); if ($value instanceof DateTime) { $value = Carbon::instance($value); } if ($this->needsTimeZoneSet($value)) { $value->setTimezone($this->time_zone); } return $value; }
/** * Implements FormatterInterface->format(). * * @param object $tweet Tweet to format * @return string Formatted tweet */ public function format(\stdClass $tweet) { $created_at = new \DateTime($tweet->created_at); $created_at_relative = Carbon::instance($created_at)->diffForHumans(); $user_created_at = new \DateTime($tweet->user->created_at); $user_created_at_relative = Carbon::instance($user_created_at)->diffForHumans(); $url = 'https://twitter.com/' . $tweet->user->screen_name . '/status/' . $tweet->id_str; $replacements = array('%coordinates%' => $tweet->coordinates, '%created_at.formatted%' => $created_at->format($this->datePattern), '%created_at.relative%' => $created_at_relative, '%created_at%' => $tweet->created_at, '%geo%' => $tweet->geo, '%id_str%' => $tweet->id_str, '%in_reply_to_screen_name%' => $tweet->in_reply_to_screen_name, '%in_reply_to_status_id_str%' => $tweet->in_reply_to_status_id_str, '%in_reply_to_user_id_str%' => $tweet->in_reply_to_user_id_str, '%place%' => isset($tweet->place->full_name) ? $tweet->place_full_name : '', '%retweet_count%' => $tweet->retweet_count, '%source%' => $tweet->source, '%text%' => html_entity_decode($tweet->text), '%url%' => $url, '%user.created_at.formatted%' => $user_created_at->format($this->datePattern), '%user.created_at.relative%' => $user_created_at_relative, '%user.created_at%' => $tweet->user->created_at, '%user.description%' => $tweet->user->description, '%user.favourites_count%' => $tweet->user->favourites_count, '%user.followers_count%' => $tweet->user->followers_count, '%user.friends_count%' => $tweet->user->friends_count, '%user.id_str%' => $tweet->user->id_str, '%user.lang%' => $tweet->user->lang, '%user.listed_count%' => $tweet->user->listed_count, '%user.location%' => $tweet->user->location, '%user.name%' => $tweet->user->name, '%user.profile_background_color%' => $tweet->user->profile_background_color, '%user.profile_background_image_url_https%' => $tweet->user->profile_background_image_url_https, '%user.profile_background_image_url%' => $tweet->user->profile_background_image_url, '%user.profile_image_url_https%' => $tweet->user->profile_image_url_https, '%user.profile_image_url%' => $tweet->user->profile_image_url, '%user.profile_link_color%' => $tweet->user->profile_link_color, '%user.profile_sidebar_border_color%' => $tweet->user->profile_sidebar_border_color, '%user.profile_sidebar_fill_color%' => $tweet->user->profile_sidebar_fill_color, '%user.profile_text_color%' => $tweet->user->profile_text_color, '%user.screen_name%' => $tweet->user->screen_name, '%user.statuses_count%' => $tweet->user->statuses_count, '%user.time_zone%' => $tweet->user->time_zone, '%user.url%' => $tweet->user->url, '%user.utc_offset%' => $tweet->user->utc_offset); $formatted = str_replace(array_keys($replacements), array_values($replacements), $this->pattern); return $formatted; }
/** * Returns Time-To-Live in seconds. * * @param int|DateTime $minutes the duration of lifetime. * @param int $now the user defined current time. * @return int the caluculated ttl value. */ public static function getTTL($minutes, $now = null) { if ($minutes instanceof DateTime) { $from = -Carbon::instance($minutes)->diffInSeconds($now, false); if ($from < 0) { //TODO: Implement appropriate exception. throw new Exception('invalid time specified.'); } return $from; } return $minutes * 60; }
public function run() { Conference::truncate(); $faker = Faker::create(); $user_ids = collect(User::lists('id')); $conference_names = collect(['MegaAwesomeCon', 'SuperPHP', 'ActiveRecordCon', 'ConCon', 'GoodJobFest', 'TightenFest', 'UltraMegaCon', 'ArbysCon']); foreach (range(1, 30) as $i) { $starts_at = $faker->dateTimeBetween('now', '3 years'); $cfp_starts_at = $faker->dateTimeBetween('now', $starts_at); Factory::create('conference', ['author_id' => $user_ids->random(), 'title' => $conference_names->random() . " {$starts_at->format('Y')}", 'description' => $faker->sentence, 'starts_at' => $starts_at, 'ends_at' => Carbon::instance($starts_at)->addDays(2), 'cfp_starts_at' => $cfp_starts_at, 'cfp_ends_at' => Carbon::instance($cfp_starts_at)->addDays(rand(15, 30))]); } }
/** * Tests if the Time package works correctly. */ public function testGetTTL() { $from = new DateTime("2015-05-27 22:30:15.638276"); $until = new DateTime("2015-05-27 22:31:15.889342"); // Checks if the unitary argument's functionality works fine. $this->assertEquals(3600, Time::getTTL(60)); // Checks if the binary argument's functionality works fine. $this->assertEquals(60, Time::getTTL($until, Carbon::instance($from))); // Checks if the expected Exception will be thrown. $this->setExpectedException(Exception::class); Time::getTTL($now, Carbon::instance($expire)); }
public function testGetHistoricalMeetings() { $startDate = Carbon::now('UTC'); $startDate->subMonth(); $endDate = Carbon::now('UTC'); $meetings = $this->meetingService->getHistoricalMeetings($startDate, $endDate); $this->assertNotEmpty($meetings); $actualMeeting = $meetings[0]; $this->assertNotNull($actualMeeting); $this->assertInstanceOf('\\kenobi883\\GoToMeeting\\Models\\Meeting', $actualMeeting); $actualDate = Carbon::instance($actualMeeting->getDate()); $this->assertTrue($actualDate->between($startDate, $endDate)); }
/** * @inheritdoc */ public function isValid($value) { $this->setValue($value); $cronExpression = CronExpression::factory($value); $firstRun = Carbon::instance($cronExpression->getNextRunDate()); $secondRun = Carbon::instance($cronExpression->getNextRunDate($firstRun)); $dateWithAddedInterval = Carbon::instance($firstRun->add($this->interval)); if (!$secondRun->gte($dateWithAddedInterval)) { $this->error(self::INVALID); return false; } return true; }
protected function updateConquerableStations() { $stationLastUpdate = $this->em->getRepository('AppBundle:ApiUpdate')->getLastUpdateByType(ApiUpdate::CONQUERABLE_STATIONS); $update = false; if ($stationLastUpdate === null || $this->now->diffInHours(Carbon::instance($stationLastUpdate->getCreatedAt())) > 24) { $this->log->info('Updating Conquerable Stations'); $this->evedata_registry->get(ConquerableStationManager::getName())->updateConquerableStations(); $update = $this->update_service->createApiUpdate(ApiUpdate::CACHE_STYLE_LONG, ApiUpdate::CONQUERABLE_STATIONS, true); $this->em->persist($update); $update = true; } return $update; }