本文整理汇总了PHP中Carbon\Carbon类的典型用法代码示例。如果您正苦于以下问题:PHP Carbon类的具体用法?PHP Carbon怎么用?PHP Carbon使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Carbon类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getFilters
/**
* Dodatkowe filtry Twig zwiazane z formatowaniem danych uzytkownika
*
* @return array
*/
public function getFilters()
{
return [new Twig_SimpleFilter('format_date', function ($dateTime, $diffForHumans = true) {
$format = Auth::check() ? auth()->user()->date_format : '%Y-%m-%d %H:%M';
if (!$dateTime instanceof Carbon) {
$dateTime = new Carbon($dateTime);
}
$now = Carbon::now();
if (!$diffForHumans) {
return $dateTime->formatLocalized($format);
} elseif ($dateTime->diffInHours($now) < 1) {
return $dateTime->diffForHumans(null, true) . ' temu';
} elseif ($dateTime->isToday()) {
return 'dziś, ' . $dateTime->format('H:i');
} elseif ($dateTime->isYesterday()) {
return 'wczoraj, ' . $dateTime->format('H:i');
} else {
return $dateTime->formatLocalized($format);
}
}), new Twig_SimpleFilter('timestamp', function ($dateTime) {
if ($dateTime instanceof Carbon) {
return $dateTime->getTimestamp();
} else {
return strtotime($dateTime);
}
})];
}
示例2: getDateAdmissionAttribute
public function getDateAdmissionAttribute()
{
$now = new Carbon();
$dt = new Carbon($this->created_at);
$dt->setLocale('es');
return $dt->diffForHumans($now);
}
示例3: getTransactionsByMember
public function getTransactionsByMember(Corporation $corp, array $member_ids, Carbon $date)
{
$start = $date->copy();
$start->subMonth()->setTime(0, 0, 0);
$end = $date->copy();
$end->setTime(23, 59, 59);
$sql = 'SELECT jt.owner_id2, group_concat(DISTINCT jt.id) as ids
FROM journal_transactions as jt
LEFT JOIN accounts as acc on jt.account_id=acc.id
WHERE acc.corporation_id = :corp_id
AND jt.owner_id2 in ( :owner_ids )
AND jt.date >= :start_date
AND jt.date <= :end_date
GROUP BY jt.owner_id2';
$rsm = new ResultSetMappingBuilder($this->getEntityManager());
$rsm->addRootEntityFromClassMetadata('AppBundle\\Entity\\JournalTransaction', 'jt');
$rsm->addFieldResult('jt', 'owner_id2', 'owner_id2');
$rsm->addFieldResult('jt', 'ids', 'id');
$q = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$q->setParameter('corp_id', $corp->getId());
$q->setParameter('owner_ids', $member_ids, Connection::PARAM_INT_ARRAY);
$q->setParameter('start_date', $start);
$q->setParameter('end_date', $end);
$results = $q->getResult();
$real_res = [];
foreach ($results as $res) {
$ids = explode(',', $res->getId());
$rt = $this->createQueryBuilder('jt')->select('sum(jt.amount) as total_amount')->where('jt.id in (:j_ids)')->setParameter('j_ids', $ids)->getQuery()->getResult();
$r = $this->createQueryBuilder('jt')->select('jt')->where('jt.id in (:j_ids)')->setParameter('j_ids', $ids)->getQuery()->getResult();
$real_res[] = ['user' => $res->getOwnerId2(), 'total' => $rt, 'orig_ids' => $r];
}
return $real_res;
}
示例4: checkStamp
protected function checkStamp($style, $data)
{
switch ($style) {
case 1:
$search = \App\Firstcache::where('star', $data['star'])->where('size', $data['size'])->where('class', $data['class'])->where('planet', $data['planet'])->where('step', $data['step'])->first();
break;
case 2:
$search = \App\Secondcache::where('style', $data['style'])->first();
break;
case 3:
$search = \App\Thirdcache::where('star', $data['star'])->where('size', $data['size'])->where('class', $data['class'])->first();
break;
case 0:
$search = \App\Zerocache::where('id', '>', 0)->first();
break;
}
if ($search) {
$created = new Carbon($search->created_at);
$now = Carbon::now();
if ($created->diffInMinutes($now) > 180) {
$search->delete();
return false;
}
$this->chart = unserialize($search->data);
return true;
}
return false;
}
示例5: normalizeDateTime
/**
* @param null|Carbon $date
* @return null|string
*/
protected function normalizeDateTime($date)
{
if (!$date) {
return null;
}
return $date->format('Y-m-d H:i');
}
示例6: foreach
function update_episodes($parent_id, $rss)
{
foreach ($rss->channel->item as $item) {
if (!$item->enclosure) {
continue;
}
$enclosure = $item->enclosure->attributes();
$pubDate = new Carbon($item->pubDate->__toString());
$arr = array('parent_id' => $parent_id, 'title' => $this->sanitize($item->title->__toString()), 'pubDate' => $pubDate->format('U'), 'guid' => $item->guid->__toString(), 'link' => $item->link->__toString(), 'description' => $this->sanitize($item->description->__toString()), 'enclosure' => array('length' => $enclosure['length']->__toString(), 'type' => $enclosure['type']->__toString(), 'url' => $enclosure['url']->__toString()), 'itunes' => array('image' => '', 'duration' => $item->children('itunes', true)->duration->__toString(), 'explicit' => $item->children('itunes', true)->explicit->__toString(), 'keywords' => $this->sanitize($item->children('itunes', true)->keywords->__toString()), 'subtitle' => $this->sanitize($item->children('itunes', true)->subtitle->__toString())), 'raw' => $item->asXml());
$node = $item->children('itunes', true)->image;
// Needed to force evaluation
if ($node) {
$itunes_image = $node->attributes();
$arr['itunes']['image'] = $itunes_image['href']->__toString();
}
$items[] = $arr;
}
usort($items, function ($a, $b) {
if ($a['pubDate'] == $b['pubDate']) {
return 0;
}
if ($a['pubDate'] < $b['pubDate']) {
return 1;
}
return -1;
});
$items = array_slice($items, 0, RECAST_EPISODE_LIMIT);
for ($i = 0; $i < count($items); $i++) {
self::process_episode($items[$i]);
}
$args = array('posts_per_page' => -1, 'offset' => 0, 'post_type' => 'episode', 'meta_key' => 'podcast_id', 'meta_value' => $parent_id);
$q = new WP_Query($args);
update_post_meta($parent_id, 'episode_count', $q->found_posts);
}
示例7: canReserveNow
public function canReserveNow(User $user, Trip $trip)
{
$bonus = $this->karmaService->bonus($user);
$departure = new Carbon($trip->leaves_at);
$canReserveAt = $departure->subMinutes(self::BOOKING_TIME + $bonus);
return !$canReserveAt->isFuture();
}
示例8: setEnd
public function setEnd(Carbon $endDate)
{
$end = new Google_Service_Calendar_EventDateTime();
$end->setTimeZone("Europe/Madrid");
$end->setDateTime($endDate->toAtomString());
$this->attributes->setEnd($end);
}
示例9: month
/**
* @param string $year
* @param string $month
*
* @param bool $shared
*
* @return \Illuminate\View\View
*/
public function month($year = '2014', $month = '1', $shared = false)
{
$start = new Carbon($year . '-' . $month . '-01');
$subTitle = trans('firefly.reportForMonth', ['month' => $start->formatLocalized($this->monthFormat)]);
$subTitleIcon = 'fa-calendar';
$end = clone $start;
$incomeTopLength = 8;
$expenseTopLength = 8;
if ($shared == 'shared') {
$shared = true;
$subTitle = trans('firefly.reportForMonthShared', ['month' => $start->formatLocalized($this->monthFormat)]);
}
$end->endOfMonth();
$accounts = $this->helper->getAccountReport($start, $end, $shared);
$incomes = $this->helper->getIncomeReport($start, $end, $shared);
$expenses = $this->helper->getExpenseReport($start, $end, $shared);
$budgets = $this->helper->getBudgetReport($start, $end, $shared);
$categories = $this->helper->getCategoryReport($start, $end, $shared);
$balance = $this->helper->getBalanceReport($start, $end, $shared);
$bills = $this->helper->getBillReport($start, $end);
Session::flash('gaEventCategory', 'report');
Session::flash('gaEventAction', 'month');
Session::flash('gaEventLabel', $start->format('F Y'));
return view('reports.month', compact('start', 'shared', 'subTitle', 'subTitleIcon', 'accounts', 'incomes', 'incomeTopLength', 'expenses', 'expenseTopLength', 'budgets', 'balance', 'categories', 'bills'));
}
示例10: change_password
public function change_password($tmp_code = null)
{
$tmp_check = false;
if (!Auth::check()) {
$code_created = new Carbon($this->tmp_code_created);
$tmp_check = !empty($this->tmp_code) && $this->tmp_code == $tmp_code && $code_created->diff(new Carbon())->days <= 7;
if (!$tmp_check) {
FormMessage::add('tmp_code', 'The code was incorrect');
return false;
}
}
$details = Request::all();
$rules = array('new_password' => 'required|confirmed|min:4');
if (!($tmp_check || Auth::check() && Auth::action('user.edit') && Auth::user()->id != $this->id)) {
$rules['current_password'] = 'required';
}
$v = Validator::make($details, $rules);
if ($v->passes()) {
// check password
if (!empty($rules['current_password']) && !Hash::check($details['current_password'], $this->password)) {
FormMessage::add('current_password', 'The current password was incorrect');
return false;
}
// if user can change his password then change it
if (Auth::action('account.password', ['user_id' => $this->id]) || Auth::check() && Auth::action('user.edit')) {
$this->password = Hash::make($details['new_password']);
$this->tmp_code = '';
$this->save();
return true;
}
} else {
FormMessage::set($v->messages());
}
return false;
}
示例11: save
public function save(Request $request)
{
$titulo = $request->titulo;
$idtutor = $request->idtutor;
$idrevisor = $request->idrevisor;
$idlinea = $request->type;
$descripcion = $request->descripcion;
//obtenemos el campo file definido en el formulario
$file = $request->file('archivo');
//obtenemos el nombre del archivo
$nombre = $file->getClientOriginalName();
$url = storage_path('app/') . $nombre;
$messages = ['mimes' => 'Solo se permiten Archivos .pdf, .doc, .docx.'];
$validator = Validator::make(['titulo' => $titulo, 'file' => $file, 'nombre' => $nombre], ['titulo' => 'required|max:255', 'file' => 'mimes:doc,docx,pdf'], $messages);
$message = 'f';
if ($validator->fails()) {
return redirect('sistema/nuevotrabajo')->withErrors($validator);
}
$carbon = new Carbon();
//indicamos que queremos guardar un nuevo archivo en el disco local
\Storage::disk('local')->put($nombre, \File::get($file));
$nuevo_Trabajo = new Trabajo();
$nuevo_Trabajo->titulo = $titulo;
$nuevo_Trabajo->nombreArchivo = $nombre;
$nuevo_Trabajo->rutaArchivo = $url;
$nuevo_Trabajo->user_id = Auth::user()->id;
$nuevo_Trabajo->tutor_id = $idtutor;
$nuevo_Trabajo->linea_id = $idlinea;
$nuevo_Trabajo->Descripcion = $descripcion;
$nuevo_Trabajo->fecha = $carbon->now(new \DateTimeZone('America/La_Paz'));
$nuevo_Trabajo->save();
return redirect('sistema/nuevotrabajo')->with(['success' => ' ']);
}
示例12: store
public function store()
{
$id = $this->request->input('id');
$input = $this->request->only(['provider', 'text', 'link', 'image']);
$categories = $this->request->input('categories');
$inputSchedule = $this->request->only(['schedule_date', 'schedule_time']);
if ($input['provider'] == 'weblink' && !$input['link']) {
throw new Exception('The "link" argument is missing', 1);
}
$post = (int) $id ? Post::find($id)->fill($input) : new Post($input);
if ($inputSchedule['schedule_date']) {
$time = explode(':', $inputSchedule['schedule_time']);
$date = new Carbon($inputSchedule['schedule_date']);
if (count($time) > 1) {
$date->setTime($time[0], $time[1]);
}
if ($date->timestamp > time()) {
$post->posted_at = $date;
}
} else {
$post->posted_at = new Carbon();
}
$post->user_id = $this->auth->id();
$post->save();
if (count($categories)) {
$post->categories()->sync($categories);
} else {
$post->categories()->detach();
}
$post->provider_id = $post->id;
$success = $post->save();
$job = (new PublishPost($post))->onQueue('publish');
$queued = $this->dispatch($job);
return compact('success', 'queued');
}
示例13: checkinAction
/**
* @param Request $request
* @param $id
* @param $code
*
* @return array|RedirectResponse
* @Template()
*/
public function checkinAction(Request $request, $id, $code)
{
/* @var $ticket Ticket */
$ticket = $this->ticketRepo->getTicketByIdAndCode($id, $code)->getOrThrow(new NotFoundHttpException('Unknown ticket.'));
// Do not allow double checkins
if ($ticket->isCheckedIn()) {
throw new BadRequestException('Already checked in!');
}
// Do not allow checkins on the wrong day
/* @var $event Event */
$event = $this->eventRepo->getNextEvent()->getOrThrow(new AccesDeniedHttpException('No event.'));
$now = new Carbon();
$start = Carbon::createFromTimestamp($event->getStart()->getTimestamp());
$start->setTime(0, 0, 0);
if ($ticket->isSunday()) {
$start->modify('+1day');
}
$end = clone $start;
$end->setTime(23, 59, 59);
if (!$now->between($start, $end)) {
throw new BadRequestException('Wrong day!');
}
// Record checkin
$command = new CheckinCommand();
$command->ticket = $ticket;
$this->commandBus->handle($command);
return array('ticket' => $ticket);
}
示例14: fire
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
//
$map = Map::findOrFail($this->argument('map'));
$minimap = $map->minimap;
if (!$minimap->locked || $this->option('force')) {
// Call dibs on editing this minimap
$supernow = new Carbon();
$this->info('[' . Carbon::now() . '] Locking and processing map ' . $map->id);
$minimap->updated_at = new \DateTime();
$minimap->locked = true;
$minimap->save();
// Load the tiles. May take some time. =)
$tiles = Tile::where('mapid', $map->id)->where('posz', 7)->get();
// Prepare the canvas, maestro!
\OTWorlds\MinimapPainter::$filename = $minimap->path;
\OTWorlds\MinimapPainter::load($map->width, $map->height);
foreach ($tiles as $tile) {
\OTWorlds\MinimapPainter::paint(intval($tile->posx), intval($tile->posy), intval($tile->itemid));
}
// Finish up
\OTWorlds\MinimapPainter::save();
// Let other processes edit this map again
$minimap->locked = false;
$minimap->save();
$donenow = new Carbon();
$this->info('[' . $donenow->now() . '] Done. Processed ' . $tiles->count() . ' tiles in ' . $donenow->diffInSeconds($supernow) . ' seconds.');
} else {
$this->error('Minimap is locked. Either another process is using it, or the last one crashed. Use --force to ignore.');
}
}
示例15: add
public function add($start = null, $end = null)
{
$groups = CustomerGroup::lists('groupname', 'id');
$start = new Carbon($start);
$end = new Carbon($end);
return view('event.add')->with('groups', $groups)->with('start', $start->toTimeString())->with('end', $end->toTimeString())->with('dayOfWeek', $start->dayOfWeek)->with('daysOfWeek', $this->daysOfWeek())->with('body', 'event-edit');
}