当前位置: 首页>>代码示例>>PHP>>正文


PHP Carbon::createFromFormat方法代码示例

本文整理汇总了PHP中Carbon\Carbon::createFromFormat方法的典型用法代码示例。如果您正苦于以下问题:PHP Carbon::createFromFormat方法的具体用法?PHP Carbon::createFromFormat怎么用?PHP Carbon::createFromFormat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Carbon\Carbon的用法示例。


在下文中一共展示了Carbon::createFromFormat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: parse

 /**
  * @param      $string
  * @param null $path
  * @return string
  */
 public function parse($string, $path = null)
 {
     $headers = [];
     $parts = preg_split('/[\\n]*[-]{3}[\\n]/', $string, 3);
     if (count($parts) == 3) {
         $string = $parts[0] . "\n" . $parts[2];
         $headers = $this->yaml->parse($parts[1]);
     }
     $file = new SplFileInfo($path, '', '');
     $date = Carbon::createFromTimestamp($file->getMTime());
     $dateFormat = config('fizl-pages::date_format', 'm/d/Y g:ia');
     $headers['date_modified'] = $date->toDateTimeString();
     if (isset($headers['date'])) {
         try {
             $headers['date'] = Carbon::createFromFormat($dateFormat, $headers['date'])->toDateTimeString();
         } catch (\InvalidArgumentException $e) {
             $headers['date'] = $headers['date_modified'];
             //dd($e->getMessage());
         }
     } else {
         $headers['date'] = $headers['date_modified'];
     }
     $this->execute(new PushHeadersIntoCollectionCommand($headers, $this->headers));
     $viewPath = PageHelper::filePathToViewPath($path);
     $cacheKey = "{$viewPath}.headers";
     $this->cache->put($cacheKey, $headers);
     return $string;
 }
开发者ID:hscale,项目名称:fizl-pages,代码行数:33,代码来源:PageHeaderParser.php

示例2: makefilename

 public function makefilename(Request $request)
 {
     $date = Carbon::createFromFormat('d/m/Y', $request['published_at']);
     $date = $date->format('Y-m-d');
     $filename = sprintf('%s-[%s]-%s.png', $date, implode(',', $request['tags']), $this->createSlug($request['heading']));
     return ['filename' => $filename];
 }
开发者ID:antonioribeiro,项目名称:ak,代码行数:7,代码来源:Clipping.php

示例3: formatDate

 public static function formatDate($date)
 {
     $instance = Carbon::createFromFormat('Y-m-d', $date);
     setlocale(LC_TIME, 'fr_FR');
     $formatDate = $instance->formatLocalized('%d %B %Y');
     return $formatDate;
 }
开发者ID:abada,项目名称:webshop,代码行数:7,代码来源:Format.php

示例4: lastLogin

 /**
  * @return string
  */
 public function lastLogin()
 {
     if (!$this->last_login || $this->last_login == '0000-00-00 00:00:00') {
         return;
     }
     return Carbon::createFromFormat('Y-m-d H:i:s', $this->last_login)->diffForHumans();
 }
开发者ID:SocietyCMS,项目名称:User,代码行数:10,代码来源:UserPresenter.php

示例5: makeTimeStamp

 /**
  * Make timestamp
  * @param string $datetime
  * @param string $format
  * @return integer
  */
 public function makeTimeStamp($datetime, $format = 'full')
 {
     if (in_array($format, ['short', 'full'])) {
         $format = $this->getFormat($format);
     }
     return Carbon::createFromFormat($format, $datetime, $this->getTimeZone())->getTimestamp();
 }
开发者ID:jarick,项目名称:bx,代码行数:13,代码来源:DateTimeManager.php

示例6: postLogin

 public function postLogin(LoginRequest $request)
 {
     if (!Auth::attempt(['email' => $request->get('email'), 'password' => $request->get('password')], true)) {
         session()->flash('errorMessages', ['You have entered an invalid email address or password.', 'Please try again.']);
         return back()->withInput();
     }
     $user = Auth::user();
     // if the user has a plant, set welcome message
     if (count($user->plants)) {
         $plant = $user->plants()->where('isHarvested', '=', false)->orderBy(DB::raw('RAND()'))->first();
         if ($plant) {
             // set welcome message to need water or need fertilizer if the plant needs it
             $lastTimeWatered = $plant->getLastTimeWatered();
             $lastTimeFertilized = $plant->getLastTimeFertilized();
             $random = round(rand(1, 2));
             if (!$lastTimeWatered && $plant->created_at->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_water_phrase_' . $random];
             } elseif (!$lastTimeFertilized && $plant->created_at->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_fertilizer_phrase_' . $random];
             } elseif ($lastTimeWatered && Carbon::createFromFormat('Y-m-d H:i:s', $lastTimeWatered->pivot->date)->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_water_phrase_' . $random];
             } elseif ($lastTimeFertilized && Carbon::createFromFormat('Y-m-d H:i:s', $lastTimeFertilized->pivot->date)->addDay() < Carbon::now()) {
                 $status = $plant->plantCharacter['need_fertilizer_phrase_' . $random];
             } else {
                 $status = $plant->plantCharacter['welcome_phrase_' . $random];
             }
             session()->flash('message', $plant->plantCharacter->name . ': ' . $status);
         }
     }
     return redirect()->route('dashboard');
 }
开发者ID:DriesVS,项目名称:gardening-for-lazy-people,代码行数:31,代码来源:AuthController.php

示例7: getYearly

 /**
  * Render yearly panel with navigation and chart
  * @param  string $envelopeId Envelope primary key
  * @param  string|null $date Date within the year to consider (default to current year)
  * @return Illuminate\View\View|\Illuminate\Contracts\View\Factory View
  */
 public function getYearly($envelopeId, $date = null)
 {
     $envelope = Auth::user()->envelopes()->findOrFail($envelopeId);
     $date = is_null($date) ? Carbon::today() : Carbon::createFromFormat('Y-m-d', $date);
     $data = ['envelope' => $envelope, 'date' => $date, 'prevYear' => $date->copy()->subYear(), 'nextYear' => $date->copy()->addYear(), 'chart' => LineChart::forge($envelope, $date, LineChart::PERIOD_YEAR)];
     return view('envelope.development.yearly', $data);
 }
开发者ID:simondubois,项目名称:budget,代码行数:13,代码来源:DevelopmentController.php

示例8: create

    /**
     * Stores a new notification for the user.
     *
     * @param Request $request
     *
     * @return array
     */
    public function create(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'gcm_id'   => 'required|exists:users,gcm_id',
            'movie_id' => 'required|exists:movies,id',
            'date'     => 'required|date|after:today',
            'no_of_seats' => 'required_with_all:after_time,before_time|integer',
            'after_time' => 'required_with_all:no_of_seats,before_time|date_format:g\:i A',
            'before_time' => 'required_with_all:no_of_seats,after_time|date_format:g\:i A',
        ]);

        if ($validator->fails()) {
            return ['errors' => $validator->errors()->all(), 'status' => 'failed'];
        }

        $user = User::whereGcmId($request->get('gcm_id'))->firstOrFail();
        $movie = Movie::findOrFail($request->get('movie_id'));
        $date = Carbon::createFromFormat('Y-m-d', $request->get('date'))->toDateString();
        $numberOfSeats = $request->get('no_of_seats', 0);
        $afterTime = $numberOfSeats ? $request->get('after_time') : null;
        $beforeTime = $numberOfSeats ? $request->get('before_time') : null;

        if (!$movie->showtimes()->where('date', $date)->count()) {
            $user->notifications()->firstOrCreate([
                'movie_id' => $movie->id,
                'date'     => Carbon::createFromFormat('Y-m-d', $date)->toDateTimeString(),
                'sent'     => false,
                'no_of_seats' => $numberOfSeats,
                'after_time' => $afterTime,
                'before_time' => $beforeTime,
            ]);
        }

        return ['status' => 'success'];
    }
开发者ID:nikhil-pandey,项目名称:movie-notifier,代码行数:42,代码来源:NotificationController.php

示例9: longestPath

 private function longestPath(&$tasks, &$trail = [])
 {
     if (empty($tasks)) {
         return 0;
     }
     $max = ['weight' => 0, 'trail' => []];
     foreach ($tasks as &$task) {
         if (!$task['from'] || !$task['to']) {
             continue;
         }
         $newTrail = $trail;
         $newTrail[] =& $task;
         $diff = Carbon::createFromFormat('Y-m-d', $task['from'])->diffInDays(Carbon::createFromFormat('Y-m-d', $task['to']));
         $weight = $diff + $this->longestPath($task['slaves'], $newTrail);
         if ($max['weight'] < $weight) {
             $max['weight'] = $weight;
             $max['trail'] = $newTrail;
         }
     }
     if (empty($trail)) {
         //At top level
         foreach ($max['trail'] as &$task) {
             $task['critical'] = true;
         }
     }
     foreach ($max['trail'] as &$task) {
         if (!in_array($task, $trail)) {
             $trail[] =& $task;
         }
     }
     return $max['weight'];
 }
开发者ID:titus-toia,项目名称:treabar,代码行数:32,代码来源:CriticalPath.php

示例10: testWithDaysAndStartDate

 public function testWithDaysAndStartDate()
 {
     $startDate = Carbon::createFromFormat("Y-m-d", "2014-03-01");
     $request = new Shows(get_token(), $startDate, 25);
     $this->assertContains("25", (string) $request->getDays());
     $this->assertContains("2014-03-01", (string) $request->getStartDate());
 }
开发者ID:ValentinGot,项目名称:trakt-api-wrapper,代码行数:7,代码来源:ShowsTest.php

示例11: store

 /**
  * Store a newly created resource in storage.
  *
  * @param  Request  $request
  * @return Response
  */
 public function store(Request $request)
 {
     $path = config('enzo.uploads.comprovante_aporte.path');
     $data_aporte = Carbon::createFromFormat('d/m/Y', $request->data)->toDateString();
     // Prepara os dados para que seja feito o upload do arquivo
     $file = $request->file('comprovante');
     $extension = $file->getClientOriginalExtension();
     $newFilename = $request->investidor_id . '_' . str_replace(['.', ','], '', $request->valor) . '_' . $data_aporte . '_' . str_random(2) . '.' . $extension;
     // Cria o objeto com os dados do request
     $aporte = new AporteFinanceiro();
     $aporte->valor = $request->valor;
     $aporte->data = $data_aporte;
     $aporte->comprovante_path = $newFilename;
     $aporte->observacao = $request->observacao;
     $aporte->investidor_id = $request->investidor_id;
     $upload = new UploadFile();
     $retornoUpload = $upload->upload($path, $newFilename, $file);
     if ($retornoUpload['cod'] == 0) {
         return redirect()->back()->with('status', $retornoUpload['msg']);
     }
     // se deu certo o upload do comprovante, salva no banco o "aporte financeiro"
     try {
         $aporte->save();
     } catch (Exception $e) {
         $upload->deleteFile();
         //se deu erro ao salvar no banco, tem q apagar o arquivo q foi upado
         var_dump($e->getMessage());
         //@TODO confirmar se o catch interrompe a execuçao do codigo
     }
     return redirect()->route('aporte-financeiro.index')->with('status', "Aporte financeiro cadastrado com sucesso!");
 }
开发者ID:andradedaniel,项目名称:enzo,代码行数:37,代码来源:AporteFinanceiroController.php

示例12: asDateTime

 /**
  * 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);
 }
开发者ID:npmweb,项目名称:laravel-base,代码行数:31,代码来源:BaseModel.php

示例13: calculateTimerTime

 private function calculateTimerTime($start, $finish)
 {
     $carbon_start = Carbon::createFromFormat('Y-m-d H:i:s', $start);
     $carbon_finish = Carbon::createFromFormat('Y-m-d H:i:s', $finish);
     $time = $carbon_finish->diff($carbon_start);
     return $time;
 }
开发者ID:JennySwift,项目名称:project-tracker,代码行数:7,代码来源:ProjectSeeder.php

示例14: update

 public function update(Request $request)
 {
     $rules = ['period_id' => 'required|exists:periods,id', 'name' => 'required|min:4|max:255', 'start' => 'required|date', 'end' => 'required|date'];
     $messages = ['period_id.exists' => 'El periodo indicado no existe.', 'name.required' => 'Es necesario asignar un nombre al periodo.', 'name.min' => 'Ingrese un nombre adecuado.', 'start.required' => 'Es necesario definir la fecha de inicio.', 'end.required' => 'Es necesario definir la fecha de fin.'];
     $v = Validator::make($request->all(), $rules, $messages);
     if ($v->fails()) {
         return ['success' => false, 'errors' => $v->getMessageBag()->toArray()];
     }
     // Getting the period that will be updated
     $period = Period::find($request->get('period_id'));
     $year = $period->school_year;
     // Custom validation
     $name = $request->get('name');
     $start = Carbon::createFromFormat("Y-m-d", $request->get('start'));
     $end = Carbon::createFromFormat("Y-m-d", $request->get('end'));
     if ($start < $year->start) {
         $errors['start'] = 'La fecha de inicio debe ser posterior al inicio del año lectivo.';
     }
     if ($end > $year->end) {
         $errors['end'] = 'La fecha de fin debe ser anterior al fin del año lectivo.';
     }
     if (isset($errors)) {
         return ['success' => false, 'errors' => $errors];
     }
     // Finally, saving the changes
     $period->name = $name;
     $period->start = $start;
     $period->end = $end;
     $period->save();
     return ['success' => true, 'name' => $period->name, 'start' => $period->start_format, 'end' => $period->end_format];
 }
开发者ID:JCarlosR,项目名称:sistema-academico,代码行数:31,代码来源:PeriodController.php

示例15: relative

 public static function relative($string)
 {
     if (empty($string)) {
         return '';
     }
     return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $string)->diffForHumans();
 }
开发者ID:joshreisner,项目名称:avalon,代码行数:7,代码来源:Dates.php


注:本文中的Carbon\Carbon::createFromFormat方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。