public function solicitar(Request $request) { $inputs = \Input::all(); // dd($request->all()); try { // $this->_validador->validate($inputs); $registro = new Solicitudes(); $fecha = date_create_from_format('j.m.Y h:i a', $request->get('fecha')); $fecha = $fecha->format('Y-m-j H:i:s'); $registro->cliente = Auth::user()->id; $registro->especificaciones = $request->get('mensaje'); $registro->fechayhora = $fecha; $registro->estado = 0; $registro->save(); foreach ($request->get('servicios') as $servicio => $sid) { $ser = new Serviciossolicitados(); $ser->solicitud = $registro->id; $ser->servicio = $sid; $ser->save(); } dd('yeh'); return \Redirect::route('publicCuenta')->with('alerta', 'Tu reservacion!'); } catch (ValidationException $e) { return \Redirect::route('publicReservacion')->withInput()->withErrors($e->get_errors()); } }
/** * Returns TRUE if submitted value validates according to rule * * @return boolean * @see \TYPO3\CMS\Form\Validation\ValidatorInterface::isValid() */ public function isValid() { if ($this->requestHandler->has($this->fieldName)) { $value = $this->requestHandler->getByMethod($this->fieldName); if (function_exists('strptime')) { $parsedDate = strptime($value, $this->format); $parsedDateYear = $parsedDate['tm_year'] + 1900; $parsedDateMonth = $parsedDate['tm_mon'] + 1; $parsedDateDay = $parsedDate['tm_mday']; return checkdate($parsedDateMonth, $parsedDateDay, $parsedDateYear); } else { // %a => D : An abbreviated textual representation of the day (conversion works only for english) // %A => l : A full textual representation of the day (conversion works only for english) // %d => d : Day of the month, 2 digits with leading zeros // %e => j : Day of the month, 2 digits without leading zeros // %j => z : Day of the year, 3 digits with leading zeros // %b => M : Abbreviated month name, based on the locale (conversion works only for english) // %B => F : Full month name, based on the locale (conversion works only for english) // %h => M : Abbreviated month name, based on the locale (an alias of %b) (conversion works only for english) // %m => m : Two digit representation of the month // %y => y : Two digit representation of the year // %Y => Y : Four digit representation for the year $dateTimeFormat = str_replace(array('%a', '%A', '%d', '%e', '%j', '%b', '%B', '%h', '%m', '%y', '%Y'), array('D', 'l', 'd', 'j', 'z', 'M', 'F', 'M', 'm', 'y', 'Y'), $this->format); $dateTimeObject = date_create_from_format($dateTimeFormat, $value); if ($dateTimeObject === FALSE) { return FALSE; } return $value === $dateTimeObject->format($dateTimeFormat); } } return TRUE; }
/** * This calculates time difference in seconds between now and given timestamp * * @param string $ts * @param string $format * @return int */ public static function timeDiff($ts, $format = 'Ymd-H:i:s') { $date = date_create_from_format($format, $ts); $now = new DateTime(); $diff = $date->diff($now); return abs($diff->days * 24 * 60 * 60 + $diff->h * 60 * 60 + $diff->i * 60 + $diff->s); }
public function addkillAction() { $npc = $this->params()->fromPost('npc'); $killtime = $this->params()->fromPost("killtime"); if ($npc && $killtime) { $date = date_create_from_format("D M d H:i:s Y", $killtime); $npcName = rtrim($npc, "'\r"); $npcMapper = $this->getServiceLocator()->get("DB\\Mapper\\NPC"); $killMapper = $this->getServiceLocator()->get("DB\\Mapper\\Kill"); $npc = $npcMapper->findByName($npcName); if ($npc) { if ($npc->getKill() && $npc->getKill()->getCrDate() >= $date) { return new JsonModel(['statusMessage' => sprintf("Old Kill from NPC '%s'", $npcName), 'statusCode' => 1]); } $killMapper->cleanNPC($npc); $kill = new \DB\Entity\Kill(); $kill->setCrDate($date); $spawnTime = clone $date; $spawnTime->add(new \DateInterval("PT" . $npc->getSpawnInterval() . "M")); $kill->setSpawnTime($spawnTime); $kill->setNpc($npc); $kill->setSpawnInterval($npc->getSpawnWindow()); $npc->setKill($kill); $npcMapper->update($kill); // Add to Kill Log $killLog = new \DB\Entity\KillLog(); $killLog->setCrDate($date); $killLog->setNpc($npc); $npcMapper->insert($killLog); return new JsonModel(['statusMessage' => sprintf("Kill of '%s' successful added", $npcName), 'statusCode' => 0]); } return new JsonModel(['statusMessage' => sprintf("NPC with name '%s' not found", $npcName), 'statusCode' => 2]); } return new JsonModel(['statusMessage' => 'Error', 'statusCode' => 3]); }
/** * @param $data * @return int|string */ public function guardarProforma($data, $archivo) { $result = "0"; try { // var_dump($data); $date = date_create_from_format('d/m/Y', $data["fecha"]); // var_dump($date); $proforma = new Proformas(); $proforma->setAlmacen($data["almacen"]); $proforma->setIdAlmacen($data["idalmacen"]); $proforma->setIdMarca($data["idmarca"]); $proforma->setNombreArchivo($archivo["nombre_archivo"]); $proforma->setTipoArchivo($archivo["tipo_archivo"]); $proforma->setUrlArchivo($archivo["url_archivo"]); $proforma->setMarca($data["marca"]); $proforma->setEstado("NUEVO"); $proforma->setNombre($data["nombre"]); $proforma->setNroFactura($data["nro_factura"]); $proforma->setFecha($date); // $proforma->set $this->_em->persist($proforma); $this->_em->flush(); $result = $proforma->getIdProforma(); } catch (\Exception $e) { // var_dump($e); $result = $e->getMessage(); } return $result; }
function date_to_time($date, $format = "Y-m-d H:i:s") { if (!$date) { return; } return @date_format(date_create_from_format($format, $date), 'U'); }
public function reportUmurBarang() { $dari = date_format(date_create_from_format('d-m-Y', $this->dari), 'Y-m-d'); $sampai = date_format(date_create_from_format('d-m-Y', $this->sampai), 'Y-m-d'); if (empty($this->bulan)) { $whereBulan = "inventory_balance.created_at BETWEEN :dari AND :sampai"; } else { $whereBulan = "TIMESTAMPDIFF(MONTH, inventory_balance.created_at, NOW()) >= :bulan"; } $kategoriQuery = ''; if (!empty($this->kategoriId)) { $kategoriQuery = 'JOIN barang ON inventory_balance.barang_id = barang.id AND barang.kategori_id = :kategoriId'; } $command = Yii::app()->db->createCommand(); $command->select("\n t_inventory.*,\n SUM(ib.qty) total_stok,\n TIMESTAMPDIFF(MONTH, tgl_beli_awal, NOW()) umur_bulan,\n TIMESTAMPDIFF(DAY, tgl_beli_awal, NOW()) umur_hari,\n barang.barcode,\n barang.nama\n "); $command->from("\n (SELECT \n barang_id,\n SUM(qty) qty,\n SUM(qty * harga_beli) nominal,\n MIN(inventory_balance.created_at) tgl_beli_awal,\n COUNT(*) count\n FROM\n inventory_balance\n {$kategoriQuery} \n WHERE\n {$whereBulan}\n AND qty > 0\n GROUP BY barang_id\n LIMIT {$this->limit}) AS t_inventory\n "); $command->join('inventory_balance ib', 't_inventory.barang_id = ib.barang_id'); $command->join('barang', 't_inventory.barang_id = barang.id'); $command->group('barang_id'); $command->order([$this->listSortBy2()[$this->sortBy0], $this->listSortBy2()[$this->sortBy1]]); if (!empty($this->kategoriId)) { $command->bindValue(':kategoriId', $this->kategoriId); } if (empty($this->bulan)) { $command->bindValue(':dari', $dari); $command->bindValue(':sampai', $sampai); } else { $command->bindValue(':bulan', $this->opsiUmurBulan2()[$this->bulan]); } return $command->queryAll(); }
function get_user_old_ldap($email) { $attributes = ["uid" => "uid", "mail" => "mail", "givenName" => "firstname", "sn" => "lastname", "displayName" => "nick", "gender" => "gender", "birthdate" => "dob", "o" => "organization", "c" => "country", "l" => "location"]; $this->load_library("ldap_lib", "ldap"); $ds = $this->ldap->get_link(); $dn = "dc=felicity,dc=iiit,dc=ac,dc=in"; $filter = '(&(mail=' . $email . '))'; $sr = ldap_search($ds, $dn, $filter, array_keys($attributes)); $entry = ldap_first_entry($ds, $sr); if (!$entry) { return false; } $entry_data = ldap_get_attributes($ds, $entry); $user_data = []; foreach ($attributes as $key => $value) { if (isset($entry_data[$key]) && isset($entry_data[$key][0])) { $user_data[$value] = $entry_data[$key][0]; } } if (isset($user_data["dob"])) { $date = date_create_from_format('d/m/Y', $user_data["dob"]); if ($date) { $user_data["dob"] = date_format($date, "Y-m-d"); } } if (isset($user_data["firstname"]) && isset($user_data["lastname"])) { $user_data["name"] = implode(" ", [$user_data["firstname"], $user_data["lastname"]]); unset($user_data["firstname"]); unset($user_data["lastname"]); } if (isset($user_data["gender"])) { $user_data["gender"] = strtolower($user_data["gender"]); } return $user_data; }
public function postDiscount() { $id = \Input::get('id'); $rules = array('pricelist_id' => 'required', 'code' => 'required', 'expiry_date' => 'required', 'percent' => 'required|numeric|min:1|max:100'); $validation = \Validator::make(\Input::all(), $rules); if ($validation->passes()) { $pricelist_id = \Input::get('pricelist_id'); $code = \Input::get('code'); $expiry_date = \Input::get('expiry_date'); $percent = \Input::get('percent'); $pricelist = Pricelist::find($pricelist_id); // No such id if ($pricelist == null) { $errors = new \Illuminate\Support\MessageBag(); $errors->add('deleteError', "The pricelist for discount may have been deleted. Please try again."); return \Redirect::to('admin/pricelists')->withErrors($errors)->withInput(); } $newDiscount = new Discount(); $newDiscount->code = $code; $newDiscount->expiry_date = date_create_from_format('d/m/Y H:i:s', $expiry_date . ' 00:00:00'); $newDiscount->percent = $percent; $pricelist->discounts()->save($newDiscount); } else { return \Redirect::to('admin/pricelists')->withErrors($validation)->withInput(); } return \Redirect::to('admin/pricelists'); }
/** * Format validation for the value. * * @return int */ protected function formatValidate() { if ($this->value && ($format = $this->getFormat()) && date_create_from_format($format, $this->value) === false) { return static::INVALID_CODE_FORMAT; } return static::VALID_CODE_SUCCESS; }
public function handleRequestData() { $data = Input::all(); $customerData = new CustomerData(); $customerData->firstname = $data['firstname']; $customerData->lastname = $data['lastname']; $customerData->email = $data['email']; $customerData->mobile = $data['mobile']; $customerData->description = $data['description']; if ($data['appointment']) { $appointment_dt = date_create_from_format('d F Y - H:i', $data['appointment']); $customerData->appointment = $appointment_dt; } else { $customerData->appointment = null; } $customerData->save(); if ($customerData->appointment) { $customerData->appointment = $customerData->appointment->format('d F Y - H:i'); } else { $customerData->appointment = '-'; } $subject = (string) ('customer contact #' . $customerData->id); Mail::send('customers.email', array('data' => $customerData), function ($message) use($subject) { $message->to('*****@*****.**', 'AUTHOR - PRIVATE CONTACT')->from('*****@*****.**', 'PRIVATE PARK')->subject($subject); }); return Redirect::to('/'); }
public static function getDayDiff($input_date_l, $input_date_r) { $date_1 = date_create_from_format('Y-m-d', $input_date_l); $date_2 = date_create_from_format('Y-m-d', $input_date_r); $interval = date_diff($date_1, $date_2); return $interval->format('%a') + 1; }
private function checkForNews() { try { $response = (new Client())->createRequest()->setUrl($this->getCurrentFeed()->url)->send(); if (!$response->isOk) { throw new \Exception(); } $rss = simplexml_load_string($response->getContent()); $newItemsCount = 0; foreach ($rss->channel->item as $item) { if (!NewModel::findOne(['feed' => $this->getCurrentFeed()->id, 'url' => (string) $item->link])) { $new = new NewModel(); $new->feed = $this->getCurrentFeed()->id; $new->published_at = date_create_from_format(\DateTime::RSS, (string) $item->pubDate)->format('Y-m-d H:i:s'); $new->title = (string) $item->title; if (isset($item->description)) { $new->short_text = StringHelper::truncate(strip_tags((string) $item->description), 250); } $new->url = (string) $item->link; if ($new->save()) { $newItemsCount++; } } } if ($newItemsCount > 0) { \Yii::$app->session->addFlash('info', \Yii::t('user', 'Get news: ') . $newItemsCount); $this->clearOldNewsIfNeed(); \Yii::$app->cache->delete($this->getNewsCacheKey()); \Yii::$app->cache->delete($this->getFeedsCacheKey()); } } catch (Exception $e) { \Yii::$app->session->addFlash('danger', \Yii::t('user', 'Get news error')); } }
public function showresult($date = '') { if (empty($date)) { $date = date_create('now'); } else { $date = date_create_from_format('Y-m-d', $date); } $date->setTime(0, 0, 0); $today_date = date_create('now')->setTime(0, 0, 0); //block future date results if ($date > $today_date) { $datestr = $date->format('Y-m-d'); $error = 'Future date, Result not declared yet'; return view('results', compact('error', 'datestr')); } $datestr = $date->format('Y-m-d'); $current_time = intval(date('Hi')); $_results = Result::with('lottery')->with('series')->where("date", '=', $date)->orderBy('lottery_id')->orderBy('series_id')->get(); // dd($results[0]); $results = array(); $time = date(""); if (count($_results) > 0) { foreach ($_results as $_result) { if ($date == $today_date && intval($_result->lottery->draw_time) > $current_time) { continue; } if (empty($results["{$_result->lottery->draw_time}"])) { $results["{$_result->lottery->draw_time}"] = array(); } $results["{$_result->lottery->draw_time}"]["{$_result->series->code}"] = $_result->winning_number; } } $series = Series::all(); return view('results', compact('results', 'series', 'datestr')); }
/** * * @param ParamFetcher $paramFetcher Paramfetcher * * @RequestParam(name="username", nullable=false, strict=true, description="Username") * @RequestParam(name="email", nullable=false, strict=true, description="Email") * @RequestParam(name="password", nullable=false, strict=true, description="password") * @RequestParam(name="birthday", nullable=false, strict=true, description="Birthday") * @RequestParam(name="brand", nullable=false, strict=true, description="Brand") * @RequestParam(name="sex", nullable=false, strict=true, description="Sex") * */ public function postRegisterAction(ParamFetcher $paramFetcher) { $username = $paramFetcher->get('username'); $email = $paramFetcher->get('email'); $password = $paramFetcher->get('password'); $birthday = date_create_from_format('j/m/Y', $paramFetcher->get('birthday')); $brand = $paramFetcher->get('brand'); $brand = $this->getDoctrine()->getRepository('zenitthApiBundle:brands')->find($brand); $sex = $paramFetcher->get('sex'); $userManager = $this->get('fos_user.user_manager'); $user = $userManager->createUser(); $user->setUsername($username); $user->setEmail($email); $user->setPlainPassword($password); $user->setEnabled(true); $user->setRoles(array('ROLE_APPLI')); $user->setBirthdate($birthday); $user->setUserBrand($brand); $user->setSexe($sex); $user->setScore(0); $apiKey = sha1($user->getSalt() . $user->getId()); $user->setApiKey($apiKey); $userManager->updateUser($user); $clientManager = $this->container->get('fos_oauth_server.client_manager.default'); $client = $clientManager->createClient(); $client->setRedirectUris(array('')); $client->setAllowedGrantTypes(array('http://zenitth.com/grants/api_key', 'refresh_token')); $client->setUser($user); $clientManager->updateClient($client); $clientId = $client->getId() . "_" . $client->getRandomId(); $secret = $client->getSecret(); $key = $apiKey; return array('clientId' => $clientId, 'secretId' => $secret, 'key' => $key); }
/** * Create a Voucher Type * * @param VoucherType $oVoucherType The Voucher Group Entity * @throws VoucherException if the database query fails or entity has id assigned. * @returns boolean true if the insert operation was successful */ public function execute(VoucherType $oVoucherType) { $oGateway = $this->oGateway; $oVoucherBuilder = $oGateway->getEntityBuilder(); $bSuccess = false; if (false === empty($oVoucherGroup->getVoucherTypeId())) { throw new VoucherException('Unable to create new voucher type the Entity has a database id assigned already'); } try { $oQuery = $oGateway->insertQuery()->start(); foreach ($oVoucherBuilder->demolish($oVoucherType) as $sColumn => $mValue) { if ($sColumn !== 'voucher_type_id' && $sColumn !== 'voucher_enabled_to') { $oQuery->addColumn($sColumn, $mValue); } elseif ($sColumn === 'voucher_enabled_to') { // making the new copy the currrent $oQuery->addColumn('voucher_enabled_to', date_create_from_format('Y-m-d', '3000-01-01')); } } $bSuccess = $oQuery->end()->insert(); if ($bSuccess) { $oVoucherGroup->setVoucherGroupId($oGateway->lastInsertId()); } } catch (DBALGatewayException $e) { throw new VoucherException($e->getMessage(), 0, $e); } return $bSuccess; }
public static function checkDate($date, $class) { //check if set and date null //return error if (!isset($class->date) && $date == null) { //return error code and msg if there is no date set; $error = Functions::error(100, "Date is not set"); } else { if ($date == null) { //set date from class $date = $class->date; } } //check if format is right $date = date_create_from_format('d.m.Y', $date); //if format is not correct if ($date == false) { $error = Functions::error(100, "Date is not in right format (d.m.Y)"); } //get format back, no clock needed $date = date_format($date, 'd.m.Y'); //return right date //date in function getData('date') is more imporatant than set date in class return $date; }
/** * Fetch Build status for Bamboo plan * * @param array $params Params * @return array */ public function fetchStatusForBuildWidget(array $params = []) { $responseParsed = []; $auth = $this->getAuth(); $runningBuilds = $this->fetchRunningBuilds($params, $auth); $lastBuildJson = $this->request($this->getEndpointUrl(__FUNCTION__), $params, self::RESPONSE_IN_JSON, $auth); $lastBuild = $lastBuildJson['results']['result'][0]; if (!empty($runningBuilds['builds'])) { $latestRunningBuild = $runningBuilds['builds'][0]; $responseParsed['percentDone'] = $latestRunningBuild['percentageComplete']; $responseParsed['currentStatus'] = null; $responseParsed['lastCommitter'] = $this->getCommitterNames($latestRunningBuild['triggerReason']); $responseParsed['building'] = true; } else { $responseParsed['lastCommitter'] = $this->getCommitterNames($lastBuild['buildReason']); $responseParsed['currentStatus'] = $this->mapBuildStatusName($lastBuild['state']); $responseParsed['building'] = false; $responseParsed['percentDone'] = 0; } $buildTime = date_create_from_format(self::BAMBOO_DATE_FORMAT, $lastBuild['buildCompletedTime'])->getTimestamp(); $responseParsed['lastBuilt'] = gmdate(self::WIDGET_DATE_FORMAT, $buildTime); if ($responseParsed['currentStatus'] == self::JENKINS_FAILING_STATUS) { $responseParsed['averageHealthScore'] = 0; } else { $responseParsed['averageHealthScore'] = 100; } return $responseParsed; }
/** * */ public function downloadAction() { $params = $this->getRequest()->getParams(); $output = $this->getRequest()->getParam('output', 'xml'); // Check if it's allowed to perform this action $auditLog = new \Application\Model\AuditLogModel(); $this->_helper->allowed('download', $auditLog); if (!isset($params['date'])) { throw new \Application\Exceptions\InvalidArgumentException('Query param "date" not given'); } if (!isset($params['orgId']) && !isset($params['serviceProviderId'])) { throw new \Application\Exceptions\InvalidArgumentException('Query params "orgId" or "serviceProviderId" not given'); } $filters = $this->_auditLogSrv->buildFilterList($params); $result = $this->_auditLogSrv->findAll($filters); $date = date_create_from_format('Y-m-d', $params['date']); $fileName = "audit-" . ($params['serviceProviderId'] ? $params['serviceProviderId'] : $params['orgId']) . "-" . $date->format('Ymd') . "-log"; // Init view $helper = $this->_helper->output('Stream_Json'); $helper->setFilename($fileName . '.json'); if ($output == 'csv') { $helper = $this->_helper->output('Stream_Csv'); $helper->setFilename($fileName . '.csv'); } else { if ($output == 'xml') { $helper = $this->_helper->output('Stream_Xml'); $helper->setFilename($fileName . '.xml'); } } $this->view->data = $result; $helper->addHeaders(); $this->getResponse()->sendHeaders(); $this->view->render(''); $this->_helper->forceExit(); }
public function adata_edit($id) { $data = $this->request->data; $date = date_create_from_format("m\\/d\\/Y", $this->data['start_date']); $data['start_date'] = date_format($date, 'Y-m-d H:i:s'); $date = date_create_from_format("m\\/d\\/Y", $this->data['end_date']); $data['end_date'] = date_format($date, 'Y-m-d H:i:s'); $coursemodulemap = $this->CourseLessonMap->find("first", array('conditions' => array('CourseLessonMap.lesson_id =' => $id, 'CourseLessonMap.course_id =' => $data['courseid']))); $old_data = $this->Lesson->findById($id); if ($old_data['Lesson']['published'] == 0 && $data['published'] == 1) { $data['published_date'] = date('Y-m-d H:i:s'); $coursemodulemap['CourseLessonMap']['published_date'] = $data['published_date']; } else { if ($old_data['Lesson']['published'] == 1 && $data['published'] == 0) { $data['published_date'] = "0000-00-00 00:00:00"; $coursemodulemap['CourseLessonMap']['published_date'] = $data['published_date']; } } $coursemodulemap['CourseLessonMap']['published'] = $data['published']; $coursemodulemap['CourseLessonMap']['lesson_type'] = $old_data['Lesson']['type']; $this->CourseLessonMap->save($coursemodulemap); $this->Lesson->id = $id; $courseid = $this->Lesson->save($data); $this->redirect("/admin/lesson/" . $data['courseid']); }
/** * @Route("/meter/read/add", name="meterReadAdd") */ public function newMeterRead(Request $request) { $meterRead = new MeterRead(); $repository = $this->getDoctrine()->getRepository('AppBundle:Meter'); $meters = $repository->findAll(); $meterChoices = array(); foreach ($meters as $meter) { $meterChoices[$meter->getId() . ' ' . $meter->getName()] = $meter->getId(); } $builder = $this->createFormBuilder($meterRead); $builder->add('meterId', 'choice', array('choices' => $meterChoices, 'choices_as_values' => true, 'placeholder' => 'Choose a Meter ID', 'required' => true))->add('readDate', 'text', array('label' => 'Read Date:', 'required' => false, 'attr' => array('class' => 'datepicker')))->add('meterRead', 'number', array('scale' => 2, 'required' => false))->add('peak', 'number', array('scale' => 2, 'required' => false))->add('consumption', 'number', array('scale' => 2, 'required' => false))->add('totalDollars', 'money', array('required' => false))->add('save', 'submit', array('label' => 'Submit Meter Read'))->getForm(); //Convert form date string to DateTime on submit $builder->get('readDate')->addModelTransformer(new CallbackTransformer(function ($originalDescription) { return $originalDescription; }, function ($submittedDescription) { return date_create_from_format('m/d/Y', $submittedDescription); })); $form = $builder->getForm(); $meterRead->setCreated(new \DateTime()); $meterRead->setModified(new \DateTime()); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $this->saveObject($data); return $this->redirectToRoute('meterViewSingle', array('meterId' => $data->getMeterId())); } return $this->render('default/meter_read_entry.html.twig', array('form' => $form->createView())); }
/** * Migrate database schema */ public function migrate() { $dbdomain = 'db-order'; $this->msg('Adding time columns to order table', 0); if ($this->getSchema($dbdomain)->tableExists('mshop_order') === false) { $this->status('OK'); return; } $start = 0; $conn = $this->getConnection($dbdomain); $select = 'SELECT "id", "ctime" FROM "mshop_order" WHERE "cdate" = \'\' LIMIT 1000 OFFSET :offset'; $update = 'UPDATE "mshop_order" SET "cdate" = ?, "cmonth" = ?, "cweek" = ?, "chour" = ? WHERE "id" = ?'; $stmt = $conn->create($update, \Aimeos\MW\DB\Connection\Base::TYPE_PREP); do { $count = 0; $map = array(); $sql = str_replace(':offset', $start, $select); $result = $conn->create($sql)->execute(); while (($row = $result->fetch()) !== false) { $map[$row['id']] = $row['ctime']; $count++; } foreach ($map as $id => $ctime) { list($date, $time) = explode(' ', $ctime); $stmt->bind(1, $date); $stmt->bind(2, substr($date, 0, 7)); $stmt->bind(3, date_create_from_format('Y-m-d', $date)->format('Y-W')); $stmt->bind(4, substr($time, 0, 2)); $stmt->bind(5, $id, \Aimeos\MW\DB\Statement\Base::PARAM_INT); $stmt->execute()->finish(); } $start += $count; } while ($count === 1000); $this->status('done'); }
/** * @param Request $request * @param Response $response * @param $args * @return Response */ public function save(Request $request, Response $response, $args) { $id = trim($request->getHeader('id')[0]); $summary = trim($request->getHeader('summary')[0]); $description = trim($request->getHeader('description')[0]); $dueDate = trim($request->getHeader('dueDate')[0]); if (!$summary) { $response->withStatus(500); } else { try { /** * @var Ticket $ticket ; */ $ticket = null; if ($id) { $ticket = $this->em->find('App\\Entity\\Ticket', $id); } else { $ticket = new Ticket(); } $ticket->setSummary($summary); $ticket->setDescription($description); $ticket->setDueDate($dueDate ? date_create_from_format('j/m/Y', $dueDate) : null); $this->em->persist($ticket); $this->em->flush(); $this->render($response, $ticket); } catch (\Exception $e) { $response->withStatus(500); } } return $response; }
/** * Save Reservation Action */ public function saveReservation() { // Get data mapper and domain object $ReservationMapper = $this->app->ReservationMapper; $reservation = $ReservationMapper->make(); // Format date inputs $arrive = date_create_from_format('m/d/Y', $this->app->request->post('arrival_date')); $depart = date_create_from_format('m/d/Y', $this->app->request->post('departure_date')); // Get Post Data and Assign $reservation->id = $this->app->request->post('id'); $reservation->email = $this->app->request->post('email'); $reservation->name = $this->app->request->post('name'); $reservation->phone = $this->app->request->post('phone'); $reservation->property_id = $this->app->request->post('property_id'); $reservation->arrival_date = $arrive->format('Y-m-d'); $reservation->departure_date = $depart->format('Y-m-d'); $reservation->confirmed = $this->app->request->post('confirmed') ? 1 : 0; $reservation->adults = $this->app->request->post('adults') ? $this->app->request->post('adults') : 0; $reservation->children = $this->app->request->post('children') ? $this->app->request->post('children') : 0; $reservation->message = $this->app->request->post('message'); // Was the delete flag set? if ($this->app->request->post('delete') and $this->app->request->post('id')) { $ReservationMapper->delete($reservation); } else { // Otherwise save $ReservationMapper->save($reservation); } // Get new service count to add to session data $newReservationCount = $ReservationMapper->getNewReservationCount(); $session = $this->app->session; $session->setData('newReservationCount', $newReservationCount); $this->app->redirect($this->app->urlFor('listReservations')); }
/** * Приводит дату к виду yyyy-mm-dd из вида dd/mm/yyyy * @param int $date Дата (timestamp) * @return string */ public function asDateHyphen2Slash($date) { if ($date === null) { return ''; } return date_format(date_create_from_format("Y-m-d", $date), "d/m/Y"); }
public function listAction() { $request = $this->getRequest(); $form = $this->createForm(new MorbilidadType()); $form->bindRequest($request); if ($form->isValid()) { // se optienen todos los datos del formulario para ser procesado de forma individual $dateStart = date_create_from_format('d/m/Y', $form->get('dateStart')->getData()); $dateEnd = date_create_from_format('d/m/Y', $form->get('dateEnd')->getData()); $atencion = $form->get('atencion')->getData(); $genero = $form->get('genero')->getData(); $oldStart = $form->get('edadInicial')->getData(); $oldEnd = $form->get('edadFinal')->getData(); $centroCostos = $form->get('centroCostos')->getData(); // se verifica que la informacion ingresada en el formulario sea valida if ($dateStart > $dateEnd and is_numeric($oldStart) and is_numeric($oldEnd) and $oldEnd > $oldStart and $oldEnd <= 100 and $oldStart >= 0) { $this->get('session')->setFlash('error', 'Las Fechas o Las Edades No Son Correctas, Vuelva A Ingresar La Información.'); return $this->redirect($this->generateUrl('morbilidad_vista')); } // se realiza la respectiva consulta al repositorio $em = $this->getDoctrine()->getEntityManager(); $informeMorvilidad = $em->getRepository('FacturacionBundle:FacturaCargo')->findMorbilidad($atencion, $genero, $oldStart, $oldEnd, $centroCostos, $dateStart, $dateEnd); $pdf = $this->instanciarImpreso("Informe de Morbilidad "); $view = $this->renderView('FacturacionBundle:Morbilidad:morbilidadPdf.html.twig', array('dateStart' => $dateStart, 'dateEnd' => $dateEnd, 'atencion' => $atencion, 'genero' => $genero, 'oldStart' => $oldStart, 'oldEnd' => $oldEnd, 'servicio' => $centroCostos, 'informe' => $informeMorvilidad)); $pdf->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $view, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = '', $autopadding = true); $response = new Response($pdf->Output('Informe_servicio.pdf', 'I')); $response->headers->set('Content-Type', 'application/pdf'); } else { $this->get('session')->setFlash('error', 'Opcion No Validad, Vuelva A Seleccionar Una Opcion.'); return $this->redirect($this->generateUrl('morbilidad_vista')); } }
public function render($args = NULL) { parent::render($args); $this->id = (int) $args['id']; $this['termsForm']['event_id']->setValue($this->id); $event = $this->context->createServiceEvents()->get($this->id); if ($event) { $times = $this->context->createServiceTerms()->where('event_id', $this->id); if ($times->count() > 0) { foreach ($times as $value) { $terms['terms'][$value->id]['time_id'] = $value->id; $df = date_create_from_format("Y-m-d", substr($value->date_from, 0, 10)); if ($df) { $terms['terms'][$value->id]['date_from'] = $df->format('d. m. Y'); } $df = date_create_from_format("Y-m-d", substr($value->date_to, 0, 10)); if ($df) { $terms['terms'][$value->id]['date_to'] = $df->format('d. m. Y'); } $terms['terms'][$value->id]['time_from'] = $value->time_from; $terms['terms'][$value->id]['time_to'] = $value->time_to; $terms['terms'][$value->id]['visible'] = $value->visible; if ($value->every_monday) { $terms['terms'][$value->id]['every_monday'] = 1; } if ($value->every_tuesday) { $terms['terms'][$value->id]['every_tuesday'] = 1; } if ($value->every_wednesday) { $terms['terms'][$value->id]['every_wednesday'] = 1; } if ($value->every_thursday) { $terms['terms'][$value->id]['every_thursday'] = 1; } if ($value->every_friday) { $terms['terms'][$value->id]['every_friday'] = 1; } if ($value->every_saturday) { $terms['terms'][$value->id]['every_saturday'] = 1; } if ($value->every_sunday) { $terms['terms'][$value->id]['every_sunday'] = 1; } if ($value->repeat) { $terms['terms'][$value->id]['repeat'] = 1; } } $this['termsForm']->setDefaults($terms); $this['termsForm']['terms']->remove($this['termsForm']['terms'][0]); } $this->template->event = $event; $this->template->setFile(__DIR__ . "/EventTermsControl.latte"); $this->template->id = $args['id']; $this->template->new = $this->new; $this->template->render(); } else { throw new Exception('There is no event with ID #' . $this->id); } }
/** * Client timestamp range as specified in the `Robot exclusion standard` version 2.0 draft * @link http://www.conman.org/people/spc/robots2.html#format.directives.visit-time * * @param $string * @return string[]|false */ private function draftParseTime($string) { $array = explode('-', str_replace('+', '', filter_var($string, FILTER_SANITIZE_NUMBER_INT)), 3); if (count($array) !== 2 || ($fromTime = date_create_from_format('Hi', $array[0], $dtz = new DateTimeZone('UTC'))) === false || ($toTime = date_create_from_format('Hi', $array[1], $dtz)) === false) { return false; } return ['from' => date_format($fromTime, 'Hi'), 'to' => date_format($toTime, 'Hi')]; }
public function adata_add() { $data = $this->request->data; $date = date_create_from_format("m\\/d\\/Y", $this->data['validity']); $data['validity'] = date_format($date, 'Y-m-d H:i:s'); $this->PromotionalCoupon->save($data); $this->redirect("/admin/promotional/" . $data['course_id']); }
public function getVideoPublished() { if (!empty($this->interfaceObj['datestamp'])) { $d = date_create_from_format('m-d-y g:ia', $this->interfaceObj['datestamp']); return $d !== false ? $d->format("U") : ''; } return ''; }