本文整理汇总了PHP中Datetime::createFromFormat方法的典型用法代码示例。如果您正苦于以下问题:PHP Datetime::createFromFormat方法的具体用法?PHP Datetime::createFromFormat怎么用?PHP Datetime::createFromFormat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Datetime
的用法示例。
在下文中一共展示了Datetime::createFromFormat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: apply
/**
* {@inheritdoc}
*/
public function apply(base $appbox, Application $app)
{
$conn = $app['phraseanet.appbox']->get_connection();
$sql = 'SELECT date, login, ip, locked
FROM badlog
ORDER BY id ASC';
$stmt = $conn->prepare($sql);
$stmt->execute();
$rs = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$stmt->closeCursor();
$n = 1;
foreach ($rs as $row) {
$date = Datetime::createFromFormat('Y-m-d h:i:s', $row['date']);
$failure = new AuthFailure();
if ($date) {
$failure->setCreated($date);
}
$failure->setIp($row['ip']);
$failure->setLocked(!!$row['locked']);
$failure->setUsername($row['login']);
$app['EM']->persist($failure);
if (0 === $n++ % 1000) {
$app['EM']->flush();
$app['EM']->clear();
}
}
$app['EM']->flush();
$app['EM']->clear();
return true;
}
示例2: groupAbsencesByMonth
private function groupAbsencesByMonth($absences)
{
$grouped_by_month = array();
foreach ($absences as &$a) {
$a["start"] = \Datetime::createFromFormat('Y-m-d', $a["start"]);
$a["end"] = \Datetime::createFromFormat('Y-m-d', $a["end"]);
$a["count"] = 1;
if ($a["start"] < $a["end"]) {
$a["count"] = $a["start"]->diff($a["end"])->format("%a") + 0;
}
$grouped_by_month[$a["month"]][] = $a;
}
$table_array = array();
foreach ($grouped_by_month as $month_number => $absences) {
$count = 0;
$table_array[$month_number] = array();
foreach ($absences as $absence) {
$table_array[$month_number][$absence["type"]][] = $absence;
}
}
$final_table_array = array();
foreach ($table_array as $month => $grouped_by_month) {
$final_table_array[$month] = array();
$final_table_array[$month]["total"] = 0;
foreach ($grouped_by_month as $type => $grouped_by_type) {
$final_table_array[$month][$type] = array();
$final_table_array[$month][$type]["total"] = 0;
$final_table_array[$month][$type]["times"] = 0;
$final_table_array[$month][$type]["with_pay"] = 0;
$final_table_array[$month][$type]["without_pay"] = 0;
foreach ($grouped_by_type as $absence) {
$final_table_array[$month][$type]["total"] += $absence["count"];
$final_table_array[$month][$type]["times"]++;
if ($absence["with_pay"]) {
$final_table_array[$month][$type]["with_pay"]++;
} else {
$final_table_array[$month][$type]["without_pay"]++;
}
$final_table_array[$month]["total"] += $absence["count"];
}
}
}
return $final_table_array;
}
示例3: get_version
/**
* Get version
*
* @access public
* @return Datetime $version
*/
public function get_version()
{
$classname = get_class($this);
// Migration_20150922_203123_Init
list($migration, $date, $time, $name) = explode('_', $classname);
return \Datetime::createFromFormat('YmdHis', $date . $time);
}
示例4: createParticipation
public function createParticipation($user, $drink)
{
$dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
$dEndDrink = clone $dDrink;
$dEndDrink->modify('+3 hours');
$dateFormat = 'Ymd\\THis';
$icsInvite = \Swift_Attachment::newInstance()->setContentType('text/calendar;charset=UTF-8;method=REQUEST')->setBody($this->twig->render('drink/invite_ics.twig', array('user' => $user, 'drink' => $drink, 'datetimes' => array('start' => $dDrink->format($dateFormat), 'end' => $dEndDrink->format($dateFormat), 'current' => date($dateFormat)))))->setEncoder(\Swift_Encoding::getQpEncoding());
return $this->mailer->createMessage()->setSubject('[Aperophp.net] Inscription à un ' . $drink['kind'])->setFrom(array('noreply@aperophp.net'))->setTo(array($user['email']))->setBody($this->twig->render('drink/participation_mail.html.twig', array('user' => $user, 'drink' => $drink)), 'text/html')->attach($icsInvite);
}
示例5: getTimeToUtc
/**
* Transforme une chaine date au format time CDA
*
* @param String $date String
* @param bool $naissance false
*
* @return string
*/
function getTimeToUtc($date, $naissance = false)
{
if (!$date) {
return null;
}
if ($naissance) {
$date = Datetime::createFromFormat("Y-m-d", $date);
return $date->format("Ymd");
}
$timezone = new DateTimeZone(CAppUI::conf("timezone"));
$date = new DateTime($date, $timezone);
return $date->format("YmdHisO");
}
示例6: saveAction
public function saveAction(Request $request)
{
$params = $request->all();
$params['day'] = Date::conversion($params['day']);
$request->replace($params);
unset($params['_token'], $params['q']);
$routeBack = $request->get('redirect', false);
if (!$routeBack) {
$routeBack = 'hours-control.new';
if (isset($params['id']) && (int) $params['id'] > 0) {
$routeBack = 'hours-control.edit';
}
}
if ($request->getMethod() == 'POST') {
// saving data!
$isValid = $this->repository->validateRequest($request);
if (!is_bool($isValid)) {
$request->session()->flash('message', "Invalid data, please check the following errors: ");
$request->session()->flash('validationErrros', $isValid);
$formattedDate = \Datetime::createFromFormat('Y-m-d', $request->get('day'));
$request->replace(['day' => $formattedDate->format('d/m/Y')]);
return redirect()->route($routeBack, [$routeBack == 'hours-control.edit' ? $params['id'] : null])->withInput()->with('validationErrors', $isValid);
}
//update
if ($routeBack == 'hours-control.edit') {
$hourControl = $this->repository->findById($params['id']);
if (!$hourControl) {
$request->session()->flash('message', "Register [{$params['id']}] not found");
return redirect('hours-control');
}
$hourControl = HoursControl::findOrNew($params['id']);
$hourControl->fill($params);
$hourControl->update();
$request->session()->flash('message', "Register [{$hourControl->task}] updated successfully!");
$request->session()->flash('success', true);
return redirect('hours-control');
}
//insert
$hourControls = new HoursControl();
$hourControls->create($params);
$request->session()->flash('message', "Successfully created register");
$request->session()->flash('success', true);
$redirect = $request->get('redirect', false) != false ? $request->get('redirect') : 'hours-control';
return redirect()->route($redirect);
}
$request->session()->flash('message', "Method not allowed");
return redirect('hours-control');
}
示例7: __invoke
/**
* @param array $input
* @return mixed
*/
public function __invoke(array $input)
{
if (!isset($input['month'])) {
return $this->payload->setStatus(PayloadStatus::ERROR)->setInput($input)->setOutput("Month cannot be blank e.g. '?month=2016-02'");
}
if (!\Datetime::createFromFormat('Y-m', $input['month'])) {
return $this->payload->setStatus(PayloadStatus::ERROR)->setInput($input)->setOutput("Month is incorrect format e.g. '?month=2016-02'");
}
$month_start = Carbon::createFromFormat('Y-m', $input['month'])->startOfMonth();
$month_end = Carbon::createFromFormat('Y-m', $input['month'])->endOfMonth();
$shifts = $this->shift->where('employee_id', '=', $input['id'])->where('start_time', '>=', $month_start)->where('start_time', '<=', $month_end)->get();
$hours = ['total_shifts' => $shifts->count(), 'total_hours' => 0];
foreach ($shifts as $shift) {
$hours['total_hours'] += $shift->start_time->diffInHours($shift->end_time);
}
return $this->payload->setStatus(PayloadStatus::SUCCESS)->setOutput($hours);
}
示例8: dateToTimestamp
/**
* convert date to timestamp
* @param string $value
* @param string $format
* @return string
*/
public static function dateToTimestamp($value, $format)
{
if ($value == '') {
return 0;
}
if (strpos($format, '%') !== false) {
$date = strptime($value, $format);
if (is_array($date)) {
return mktime($date['tm_hour'], $date['tm_min'], $date['tm_sec'], $date['tm_mon'] + 1, $date['tm_mday'], 1900 + $date['tm_year']);
} else {
return 0;
}
} else {
$date = \Datetime::createFromFormat($format, $value);
return $date->getTimestamp();
}
}
示例9: calendarAction
public function calendarAction()
{
$calendar = $this->getServiceLocator()->get('calendar');
$date = $this->params('date');
$startDay = \Datetime::createFromFormat('Ymd H:i:s', $date . ' 08:00:00');
$endDay = \Datetime::createFromFormat('Ymd H:i:s', $date . ' 21:00:00');
$optParams = ['orderBy' => 'startTime', 'singleEvents' => TRUE, 'timeMin' => $startDay->format(\Datetime::ATOM), 'timeMax' => $endDay->format(\Datetime::ATOM)];
$config = $this->getServiceLocator()->get('config');
$results = $calendar->events->listEvents($config['api']['googleapi']['calendarId'], $optParams);
if ($startDay->format('l') == 'Monday') {
$dates = [0 => 'Heure', 10 => '10h00', 11 => '11h00', 12 => '12h00', 13 => '13h00', 15 => '15h00', 16 => '16h00', 17 => '17h00', 18 => '18h00', 19 => '19h00', 20 => '20h00'];
} else {
$dates = [0 => 'Heure', 9 => '09h00', 10 => '10h00', 11 => '11h00', 12 => '12h00', 13 => '13h00', 15 => '15h00', 16 => '16h00'];
}
if (count($results->getItems())) {
foreach ($results->getItems() as $event) {
if ($start = $event->start->dateTime) {
$end = $event->end->dateTime;
$startDate = \Datetime::createFromFormat(\Datetime::ATOM, $start);
if (!in_array($startDate->format('l'), ['Monday', 'Tuesday'])) {
continue;
}
$endDate = \Datetime::createFromFormat(\Datetime::ATOM, $end);
for ($i = $startDate->format('H'); $i < $endDate->format('H'); $i++) {
unset($dates[$i]);
}
} else {
if ($start = $event->start->date) {
$dates = [0 => 'Aucune Place'];
}
}
}
}
if (count($dates) == 1) {
$dates = [0 => 'Aucune Place'];
}
$view = new ViewModel(array('result' => $dates));
$view->setTerminal(true);
$view->setTemplate('app/index/json.phtml');
return $view;
}
示例10: PostEvent
public function PostEvent(Request $request)
{
$eventId = $request->input('event_id');
$article = $request->input('article');
$startDate = $request->input('start_date');
$startTime = $request->input('start_time');
$endDate = $request->input('end_date');
$endTime = $request->input('end_time');
$format = 'Y-m-d H:i';
$startDateTime = \Datetime::createFromFormat($format, $startDate . ' ' . $startTime);
$endDateTime = \Datetime::createFromFormat($format, $endDate . ' ' . $endTime);
$errors = array();
if (Article::find($article) == null) {
array_push($errors, "L'article séléctionné n'est pas valide.");
}
if ($startDateTime > $endDateTime) {
array_push($errors, "La date de fin ne peut pas être antérieure à la date de début.");
}
if ($endDateTime < new \Datetime('NOW')) {
array_push($errors, "La date de fin ne peut pas être antérieure à la date actuelle.");
}
if (count($errors) == 0) {
if ($eventId == null) {
$event = new Event();
$motif = 'ajouté';
} else {
$event = Event::find($eventId);
$motif = 'modifié';
}
$event->article_id = $article;
$event->start_date = $startDateTime;
$event->end_date = $endDateTime;
$event->save();
Session::flash('success', 'Evenement #' . $event->id . ' ' . $motif . ' avec succès.');
return redirect()->route('adminEvents');
}
Session::flash('errors', $errors);
return redirect()->back()->withInput();
}
示例11:
echo "<SCRIPT language=\"javascript\">";
echo "top.location.href=\"/src/series2/accueil.php\";";
echo "</SCRIPT>";
return;
}
}
}
$data = $pool->getConfigPool($id_pool, $id_saison);
$nbre_periode = $data["nbre_periodes"];
$last_position_series = $data["last_position_series"];
$nbre_teams_in_alignement = $data["nbre_team"];
$allPlayersActive = $data['all_players_active'];
$str_fil_ariane = "Accueil";
// date de la derniere maj
$dateSec = $pool->getLastMAJ($id_pool);
$_mydate = Datetime::createFromFormat('Y-m-d H:i:s', $dateSec, $pool->timeZone);
$jour = $_mydate->format('j');
$jour_semaine = $_mydate->format('D');
switch ($jour_semaine) {
case "Mon":
$jour_semaine = "Lun.";
break;
case "Tue":
$jour_semaine = "Mar.";
break;
case "Wed":
$jour_semaine = "Mer.";
break;
case "Thu":
$jour_semaine = "Jeu.";
break;
示例12: connect
public function connect(Application $app)
{
$controllers = $app['controllers_factory'];
// *******
// ** Save/Update participation
// *******
$controllers->post('{drinkId}/register.html', function (Request $request, $drinkId) use($app) {
$returnValue = $request->isXmlHttpRequest() ? 'redirect' : $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
$drink = $app['drinks']->find($drinkId);
if (!$drink) {
$app->abort(404, 'Cet événement n\'existe pas.');
}
$now = new \Datetime('now');
$dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
if ($now > $dDrink) {
$app['session']->getFlashBag()->add('error', 'L\'événement est terminé.');
return $returnValue;
}
$user = $app['session']->get('user');
$form = $app['form.factory']->create('drink_participate');
$form->bind($request->request->get('drink_participate'));
if ($form->isValid()) {
$data = $form->getData();
$member = $app['session']->get('member');
$user = $app['session']->get('user');
if (null === $user) {
$data['user']['token'] = sha1(md5(rand()) . microtime(true) . md5(rand()));
try {
$app['users']->insert($data['user']);
} catch (\Exception $e) {
$app->abort(500, 'Impossible de vous créer un compte. Merci de réessayer plus tard.');
}
// Load User in session
$id = $app['users']->lastInsertId();
$user = $app['users']->find($id);
$app['session']->set('user', $user);
} elseif (null === $member) {
try {
$app['users']->update($data['user'], array('id' => $user['id']));
} catch (\Exception $e) {
$app->abort(500, 'Impossible de modifier votre compte. Merci de réessayer plus tard.');
}
}
// Already participating?
$participation = $app['drink_participants']->findOne($drinkId, $user['id']);
if (false !== $participation) {
$participation['percentage'] = $data['percentage'];
$participation['reminder'] = $data['reminder'];
try {
$app['drink_participants']->update($participation, array('drink_id' => $drinkId, 'user_id' => $user['id']));
} catch (\Exception $e) {
$app->abort(500, 'Impossible de sauvegarder votre participation. Merci de réessayer plus tard.');
}
$app['session']->getFlashBag()->add('success', 'Participation modifiée.');
return $returnValue;
}
$participation['percentage'] = $data['percentage'];
$participation['reminder'] = (bool) $data['reminder'];
$participation['user_id'] = $user['id'];
$participation['drink_id'] = $drinkId;
try {
$app['drink_participants']->insert($participation);
} catch (\Exception $e) {
$app->abort(500, 'Impossible de sauvegarder votre participation. Merci de réessayer plus tard.');
}
$app['session']->getFlashBag()->add('success', 'Participation ajoutée.');
if ($participation['percentage'] > 0) {
$app['mailer']->send($app['mail_factory']->createParticipation($user, $drink));
}
return $returnValue;
}
$app['session']->getFlashBag()->add('error', 'Le formulaire de participation est mal remplis.');
return $returnValue;
})->bind('_participatedrink');
// *******
// *******
// ** Delete participation
// *******
$controllers->get('{drinkId}/delete.html/{email}/{token}', function (Request $request, $drinkId, $email, $token) use($app) {
$drink = $app['drinks']->find($drinkId);
if (!$drink) {
$app->abort(404, 'Cet événement n\'existe pas.');
}
$now = new \Datetime('now');
$dDrink = \Datetime::createFromFormat('Y-m-d H:i:s', $drink['day'] . ' ' . $drink['hour']);
if ($now > $dDrink) {
$app['session']->getFlashBag()->add('error', 'L\'événement est terminé.');
return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
}
if (!$app['session']->has('user')) {
if (null === $email || null === $token) {
$app['session']->getFlashBag()->add('error', 'Connectez-vous ou utilisez le lien reçu par mail.');
return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
}
if (!($user = $app['users']->findOneByEmailToken($email, $token))) {
$app['session']->getFlashBag()->add('error', 'Couple email/jeton invalide.');
return $app->redirect($app['url_generator']->generate('_showdrink', array('id' => $drinkId)));
}
$app['session']->set('user', $user);
}
//.........这里部分代码省略.........
示例13: getHeureLimiteAlignement
function getHeureLimiteAlignement($id_pool, $id_saison, $id_gerant, $periode)
{
$query = "SELECT hour_max_visitor,hour_max_home,date_begin,date_alignement\n\t FROM periodes\n\t\t\t\tWHERE id_pool = {$id_pool}\n\t\t\t\tAND periode = {$periode}\n\t\t\t\tAND saison_id = {$id_saison}";
$resultID = mysql_query($query, $this->handle);
$data = mysql_fetch_array($resultID, MYSQL_ASSOC);
mysql_free_result($resultID);
$hour_max_visitor = $data["hour_max_visitor"];
$hour_max_home = $data["hour_max_home"];
$date_begin = $data["date_begin"];
$date_alignement = $data["date_alignement"];
if ($date_alignement == "0000-00-00") {
list($my_year, $my_month, $my_day) = split("-", $date_begin);
$_mydate = Datetime::createFromFormat('Y-m-d', $date_begin, $this->timeZone);
} else {
list($my_year, $my_month, $my_day) = split("-", $date_alignement);
$_mydate = Datetime::createFromFormat('Y-m-d', $date_alignement, $this->timeZone);
}
$day = $_mydate->format('j');
$month = $_mydate->format('F');
$month = $this->date_getMois($month);
$year = $_mydate->format('Y');
$jour = $_mydate->format('l');
$jour = $this->date_getJour($jour);
$query = "select gerant_home,gerant_visitor\n from schedule_pool\n where id_pool = {$id_pool}\n and saison_id = {$id_saison}\n and periode = {$periode}\n and (gerant_home = {$id_gerant} or gerant_visitor = {$id_gerant})";
$resultID = mysql_query($query, $this->handle);
$data = mysql_fetch_array($resultID, MYSQL_ASSOC);
mysql_free_result($resultID);
if ($id_gerant == $data["gerant_home"]) {
$hour_max = $hour_max_home;
} else {
$hour_max = $hour_max_visitor;
}
list($hour, $min, $sec) = split(":", $hour_max);
$str = "{$jour} {$day} {$month} {$year}, " . $hour . "H" . $min;
unset($query, $resultID, $data, $hour_max_visitor, $hour_max_home, $date_begin, $date_alignement, $date, $day, $month, $year, $jour, $hour_max, $pool, $sess);
return $str;
}
示例14: DateTime
echo $date;
// update the validTo column to the current timestamp
$validTo = "UPDATE bfaTable SET validTo={$date} WHERE name={$name}";
// echo 'validTo: ';
// echo $date;
// TEMPORARILY SET TIME WHEN USER LOGGED IN
// fetch the valid from and to columns from the DB for the current user
// fetch the validFrom column from DB and assign the current timestamp
$validFrom = "SELECT validFrom FROM bfaTable WHERE name={$name}";
// find name in DB from form
$dateFrom = "";
// prepare the var for use later
if (mysqli_query($conn, $validFrom)) {
// if database gave us the validFrom, do this:
$currDate = new DateTime($validFrom["validFrom"]);
$dateFrom = Datetime::createFromFormat('Y-m-d H:i:s', $currDate)->format('Y-m-d h:i:s');
} else {
print_r('Error with validFrom');
}
echo $dateFrom;
// get that updated dateFrom
// THEN, create a variable that captures the validTo and validFrom
$totalTime = $date - $dateFrom;
// difference * 60
// round( abs( $dateFrom - $dateTo ), 0 ). " ";
echo $totalTime;
// Add THE totalTIME IN DATABASE
$updateTotalTime = "UPDATE bfaTable SET timeLogged=`timeLogged` + {$totalTime} WHERE name='{$name}' ";
// find name in DB from form
// now activate the query
$conn->query($updateTotalTime);
示例15: providerTestValues
public function providerTestValues()
{
return array('Nominal' => array("(id, name) VALUES (42, 'poney')", array('id' => 42, 'name' => 'poney')), 'empty value' => array("(id, name) VALUES (42, '')", array('id' => 42, 'name' => '')), 'null empty value' => array("(id, name) VALUES (42, NULL)", array('id' => 42, 'name' => null)), 'value integer as string' => array("(id) VALUES ('42')", array('id' => '42')), 'value float' => array("(id, name, score) VALUES (42, 'poney', 13.37)", array('id' => 42, 'name' => 'poney', 'score' => 13.37)), 'value datetime' => array("(id, name, date) VALUES (42, 'poney', '2014-03-07 13:37:42')", array('id' => 42, 'name' => 'poney', 'date' => \Datetime::createFromFormat('Y-m-d H:i:s', '2014-03-07 13:37:42'))), 'value boolean' => array("(id, name, flag) VALUES (42, 'poney', 1)", array('id' => 42, 'name' => 'poney', 'flag' => true)));
}