本文整理汇总了PHP中Carbon类的典型用法代码示例。如果您正苦于以下问题:PHP Carbon类的具体用法?PHP Carbon怎么用?PHP Carbon使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Carbon类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: dueDate
public function dueDate()
{
$settings = APSetting::first();
$generated_on = new Carbon($this->generated_on);
$generated_on->addDays($settings->payment_due_in_days);
return $generated_on->format('d M y');
}
示例2: calculateHolidays
private function calculateHolidays($country, $fromYear, $toYear)
{
$return = [];
if ($fromYear == $toYear) {
$years = [$fromYear];
} else {
$years = [$fromYear, $toYear];
}
foreach ($years as $year) {
$country_file = dirname(__DIR__) . '/data/' . $country . '.json';
$countryHolidays = json_decode(file_get_contents($country_file), true);
foreach ($countryHolidays as $countryHoliday) {
if (strstr($countryHoliday['rule'], '%Y')) {
$rule = str_replace('%Y', $year, $countryHoliday['rule']);
} elseif (strstr($countryHoliday['rule'], '%EASTER')) {
$date = new Carbon($year . '-03-21 +' . easter_days($year) . ' days');
$rule = str_replace('%EASTER', $date->format('Y-m-d'), $countryHoliday['rule']);
} elseif (in_array($country, ['BR', 'US']) && strstr($countryHoliday['rule'], '%ELECTION')) {
$rule = $this->calculateElectionDay($country, $years, $year, $countryHoliday);
} else {
$rule = $countryHoliday['rule'] . ' ' . $year;
}
if ($rule) {
$return[] = ['name' => $countryHoliday['name'], 'date' => new Carbon($rule)];
}
}
}
return $return;
}
示例3: setCreatedAt
/**
* Set the value of the "created at" attribute.
*
* @param mixed $value
* @return void
*/
public function setCreatedAt($value)
{
$this->{static::CREATED_AT} = $value;
if (!$value instanceof Carbon) {
$value = new Carbon($value);
}
$this->{static::CREATED_AT . '_gmt'} = $value->timezone('GMT');
}
示例4: getContribute
/**
* Show the board index for the user.
*
* @return Response
*/
public function getContribute()
{
$devStart = new Carbon(static::$ContributeProjectStart);
$devCarbon = new Carbon(static::$ContributePublicStart);
$donors = Payment::all();
$donationsTotal = 0;
foreach ($donors as $donor) {
$donationsTotal += $donor->amount;
}
$devEnd = clone $devCarbon;
$devTime = $donationsTotal / 100 / (double) env('CONTRIB_HOUR_COST', 10) * static::$ContributeDevInflation;
$devEnd->addHours($devTime);
return response()->json(['development_start' => $devStart->toRfc2822String(), 'development_public' => $devCarbon->toRfc2822String(), 'development_paid_until' => $devEnd->toRfc2822String(), 'donations_total' => $donationsTotal, 'donors' => $donors->toJson()]);
}
示例5: postRegistro
public function postRegistro()
{
$input = Input::all();
$reglas = array('nombre' => 'required', 'apellido' => 'required', 'celular' => 'required|numeric|unique:users', 'cedula' => 'required|numeric|unique:users', 'email' => 'required|email|unique:users', 'pin' => 'required|numeric|digits_between:0,4', 'password' => 'required|numbers|case_diff|letters|min:6|confirmed', 'password_confirmation' => 'required|min:6');
$validation = Validator::make($input, $reglas);
if ($validation->fails()) {
return Response::json(['success' => false, 'errors' => $validation->errors()->toArray()]);
}
try {
// se guarda los datos del usuario
$user = Sentry::register(array('first_name' => Input::get('nombre'), 'last_name' => Input::get('apellido'), 'email' => Input::get('email'), 'habilitar_pin' => 1, 'celular' => Input::get('celular'), 'cedula' => Input::get('cedula'), 'password' => Input::get('password'), 'pin' => Input::get('pin'), 'porcentaje' => 0.05, 'activated' => true));
$userId = $user->getId();
$token = new Token();
$token->user_id = $userId;
$token->api_token = hash('sha256', Str::random(10), false);
$token->client = BrowserDetect::toString();
$token->expires_on = Carbon::now()->addMonth()->toDateTimeString();
$token->save();
// Se autentica de una
$user_login = Sentry::findUserById($userId);
Sentry::login($user_login, false);
return Response::json(['success' => true, 'user' => $user_login, 'token' => $token->api_token]);
} catch (Cartalyst\Sentry\Users\LoginRequiredException $e) {
$error = array('usuario' => 'Email es requerido');
} catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) {
$error = array('usuario' => 'Password es requerido');
} catch (Cartalyst\Sentry\Users\UserExistsException $e) {
$error = array('usuario' => 'El Email ya está registrado');
}
return Response::json(['success' => false, 'errors' => $error]);
}
示例6: handle
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
list($rootFolder, $current, $folder) = $this->setFolder();
$counter = 1;
$measurementsCounter = 0;
$file = fopen($folder . 'file' . $counter . '.csv', "w");
$maxRows = self::MAX_ROWS - 500;
Measurement::with('station')->where('time', '>', Carbon::now()->subMonths(3))->orderBy('time', 'asc')->chunk(500, function ($measurements) use($folder, &$file, &$measurementsCounter, &$counter, $maxRows) {
if ($measurementsCounter > $maxRows) {
echo "measurements: " . $measurementsCounter . "\n";
echo "file created: " . $counter . ".csv\n";
$measurementsCounter = 0;
if (is_resource($file)) {
fclose($file);
}
$counter++;
$file = fopen($folder . 'file' . $counter . '.csv', "w");
}
foreach ($measurements as $measurement) {
$array = $measurement->toArray();
unset($array['station_id'], $array['station']['id']);
fputcsv($file, array_flatten($array));
}
$measurementsCounter += 500;
});
File::put($rootFolder . 'finished.txt', $current);
}
示例7: getIncompleteProductLoads
public function getIncompleteProductLoads($user_id)
{
//get user and in progress product requests / ideas
$user = $this->eloquent->with(['ideas' => function ($query) {
$query->where('is_fulfilled', '=', 0);
}])->with(['productRequests' => function ($query) {
$query->whereNull('product_id');
}])->find($user_id);
if (empty($user)) {
return [];
}
$user = $user->toArray();
$product_requests = $user['product_requests'];
$ideas = $user['ideas'];
//compile inprogress items
$inprogress_items = new \Collection();
foreach ($product_requests as $product_request) {
$inprogress_items->add(['type' => 'id load', 'human_time_diff' => \Carbon::createFromFormat('Y-m-d H:i:s', $product_request['created_at'])->diffForHumans(), 'created_at' => $product_request['created_at'], 'updated_at' => $product_request['updated_at'], 'id' => $product_request['id'], 'description' => $product_request['vendor'] . ' ' . $product_request['vendor_id'], 'query' => ['vendor' => $product_request['vendor'], 'vendor_id' => $product_request['vendor_id']]]);
}
foreach ($ideas as $idea) {
$inprogress_items->add(['type' => 'idea load', 'human_time_diff' => \Carbon::createFromFormat('Y-m-d H:i:s', $idea['created_at'])->diffForHumans(), 'created_at' => $idea['created_at'], 'updated_at' => $idea['updated_at'], 'id' => $idea['id'], 'description' => $idea['description'], 'query' => ['idea_description' => $idea['description']]]);
}
$inprogress_items->sortBy('created_at');
return $inprogress_items->toArray();
}
示例8: sendInvoice
public function sendInvoice(Invoice $invoice)
{
$invoice->load('invitations', 'client', 'account');
$entityType = $invoice->getEntityType();
$view = 'invoice';
$subject = trans("texts.{$entityType}_subject", ['invoice' => $invoice->invoice_number, 'account' => $invoice->account->getDisplayName()]);
foreach ($invoice->invitations as $invitation) {
if (!$invitation->user->email) {
return false;
}
if (!$invitation->contact->email) {
return false;
}
$invitation->sent_date = \Carbon::now()->toDateTimeString();
$invitation->save();
$data = ['entityType' => $entityType, 'link' => $invitation->getLink(), 'clientName' => $invoice->client->getDisplayName(), 'accountName' => $invoice->account->getDisplayName(), 'contactName' => $invitation->contact->getDisplayName(), 'invoiceAmount' => Utils::formatMoney($invoice->amount, $invoice->client->currency_id), 'emailFooter' => $invoice->account->email_footer, 'showNinjaFooter' => !$invoice->account->isPro()];
$fromEmail = $invitation->user->email;
$fromName = $invitation->user->getDisplayName();
$this->sendTo($invitation->contact->email, $fromEmail, $fromName, $subject, $view, $data);
Activity::emailInvoice($invitation);
}
if (!$invoice->isSent()) {
$invoice->invoice_status_id = INVOICE_STATUS_SENT;
$invoice->save();
}
\Event::fire('invoice.sent', $invoice);
}
示例9: run
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$videoItems = array(array("Breakfast Show!", "This is the breakfast show description."), array("BBC News"), array("BBC News 24"), array("Dragons Den"), array("Mock The Week!"), array("Some Other Show"), array("Soundbooth Sessions"), array("The LA1 Show"), array("The One Show"), array("Star Wars"), array("Sugar TV!"), array("The Incredibles"), array("University Challenge"), array("Countdown"), array("8 out of 10 Cats Does Countdown"), array("Jurassic Park"), array("Jurassic Park 2"), array("Shrek"), array("Shrek 2"), array("Shrek 3"), array("Mission Impossible"));
foreach ($videoItems as $a) {
$mediaItemVideo = new MediaItemVideo(array("is_live_recording" => rand(0, 1) ? true : false, "time_recorded" => Carbon::now()->subHour(), "description" => rand(0, 4) === 0 ? "A description that should override the general media item one." : null, "enabled" => rand(0, 1) ? true : false));
$mediaItem = new MediaItem(array("name" => $a[0], "description" => count($a) >= 2 ? $a[1] : null, "enabled" => rand(0, 1) ? true : false, "scheduled_publish_time" => Carbon::now()));
DB::transaction(function () use(&$mediaItem, &$mediaItemVideo) {
$mediaItem->save();
$mediaItem->videoItem()->save($mediaItemVideo);
});
$this->addLikes($mediaItem);
$this->addComments($mediaItem);
}
//$mediaItemLiveStream = new MediaItemLiveStream(array(
// "enabled" => true
//));
$mediaItem = new MediaItem(array("name" => "Lunchtime Show!", "description" => "This is the lunchtime show description.", "enabled" => true, "scheduled_publish_time" => Carbon::now()));
DB::transaction(function () use(&$mediaItem, &$mediaItemLiveStream) {
$mediaItem->save();
// $mediaItem->liveStreamItem()->save($mediaItemLiveStream);
});
$this->addLikes($mediaItem);
$this->addComments($mediaItem);
$this->command->info('Media items created!');
}
示例10: update
public function update($id)
{
$oss = Oss::find($id);
$oss->tanggal_oss = Carbon::createFromFormat('d/m/Y', Input::get('tanggal_oss'));
$oss->no_oss = Input::get('no_oss');
$oss->mitra_oss = Input::get('mitra_oss');
if (Input::get('nama_bantek') != '') {
$oss->nama_bantek_oss = Input::get('nama_bantek');
}
$oss->id_site = Input::get('id_site');
$oss->nama_site = Input::get('nama_site');
if (Input::get('tanggal_mulai') != '') {
$oss->tanggal_mulai_oss = Carbon::createFromFormat('d/m/Y', Input::get('tanggal_mulai'));
}
if (Input::get('tanggal_selesai') != '') {
$oss->tanggal_selesai_oss = Carbon::createFromFormat('d/m/Y', Input::get('tanggal_selesai'));
}
$oss->permasalahan_oss = Input::get('masalah');
$oss->action_oss = Input::get('action');
if (Input::get('rincian') != '') {
$oss->rincian_jasa_material_oss = Input::get('rincian');
}
if (Input::get('shopping_list') != '') {
$oss->kode_shopping_list = Input::get('shopping_list');
}
$oss->harga_oss = Input::get('harga');
$oss->req_oleh = Input::get('request');
$oss->diketahui_oleh = Input::get('approval');
$oss->save();
Session::flash('success', 'Data has been saved');
return Redirect::to('/oss');
}
示例11: toText
public function toText($txt)
{
$tab = explode('-', $txt);
$date = Carbon::createFromTimeStamp($tab[0])->toDateString();
$tab[1] == 'm' ? $day = 'matin' : ($day = 'après-midi');
return $date . ' ' . $day;
}
示例12: fire
public function fire()
{
$cacheName = $this->queueCacheName . $this->argument('aliasCacheCode');
if (!Cache::has($cacheName)) {
return;
}
$smallIds = Cache::pull($cacheName);
$profiles = Profile::whereIn('small_id', $smallIds)->get();
foreach ($profiles as $profile) {
$steamAPI = new SteamAPI('alias');
$steamAPI->setSmallId($profile->small_id);
$steamAlias = $steamAPI->run();
if ($steamAPI->error()) {
$steamAlias = [];
} else {
usort($steamAlias, array('VacStatus\\Steam\\Steam', 'aliasSort'));
}
$profile->alias = json_encode($steamAlias);
$profile->save();
$cacheName = "profile_{$profile->small_id}}";
if (!Cache::has($cachName)) {
continue;
}
$profileCache = Cache::get($cacheName);
$profileCache['alias'] = Steam::friendlyAlias($steamAlias);
if (Cache::has($cacheName)) {
Cache::forget($cacheName);
}
$expireTime = Carbon::now()->addMinutes(60);
Cache::put($cacheName, $profileCache, $expireTime);
}
}
示例13: edit
/**
* Редактирование сообщения
*/
public function edit($id)
{
if (!User::check()) {
App::abort(403);
}
if (!($guest = Guestbook::find_by_id($id))) {
App::abort('default', 'Сообщение не найдено!');
}
if (!User::isAdmin() && $guest->user_id != User::getUser('id')) {
App::abort('default', 'Редактирование невозможно, вы не автор данного сообщения!');
}
if (!User::isAdmin() && $guest->created_at < Carbon::now()->subMinutes(10)) {
App::abort('default', 'Редактирование невозможно, прошло более 10 мин.');
}
if (Request::isMethod('post')) {
$guest->token = Request::input('token', true);
$guest->text = Request::input('text');
if ($guest->save()) {
App::setFlash('success', 'Сообщение успешно изменено!');
App::redirect('/guestbook');
} else {
App::setFlash('danger', $guest->getErrors());
App::setInput($_POST);
}
}
App::view('guestbook.edit', compact('guest'));
}
示例14: store
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store()
{
$data = Input::all();
$fecha = new Carbon();
$fecha->setTimezone('America/Bogota');
$data = array_add($data, 'fecha', $fecha::now());
if (Auth::user()->avatar != null) {
$imagen = "<img class='avatar circle' src='" . Auth::user()->avatar . "'/>";
} else {
$imagen = ' <i class="fa fa-2x fa-user"></i>';
}
$data = array_add($data, 'persona', Auth::user()->nombre . " de Residencia " . Residencias::find(Auth::user()->residencia_id)->nombre . $imagen);
$data = array_add($data, 'user_id', Auth::user()->id);
$noticia = Noticias::create($data);
return $noticia;
}
示例15: index
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$exclude = \App\EventCheckin::lists('sale_checkin_id');
$ticketsales = \App\Sale::where('created_at', '>', \Carbon::parse('1/31/2016'))->whereNotIn('cart_id', $exclude)->with('cartsBySale', 'cartsBySale.product')->get();
$checkedin = \App\Sale::where('created_at', '>', \Carbon::parse('1/31/2016'))->WhereIn('cart_id', $exclude)->with('cartsBySale', 'cartsBySale.product')->get();
return view('orders.index', compact('ticketsales', 'checkedin'));
}