本文整理汇总了PHP中DateTime::createFromString方法的典型用法代码示例。如果您正苦于以下问题:PHP DateTime::createFromString方法的具体用法?PHP DateTime::createFromString怎么用?PHP DateTime::createFromString使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DateTime
的用法示例。
在下文中一共展示了DateTime::createFromString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getLastTimeModified
/**
* @return DateTime
*/
public function getLastTimeModified()
{
if ($this->_lastTimeModified === null) {
$this->_lastTimeModified = DateTime::createFromString(self::TimestampZero);
}
return $this->_lastTimeModified;
}
示例2: actionGetNewUsersData
/**
* Returns the data needed to display a New Users chart.
*
* @return void
*/
public function actionGetNewUsersData()
{
$userGroupId = craft()->request->getRequiredPost('userGroupId');
$startDateParam = craft()->request->getRequiredPost('startDate');
$endDateParam = craft()->request->getRequiredPost('endDate');
$startDate = DateTime::createFromString($startDateParam, craft()->timezone);
$endDate = DateTime::createFromString($endDateParam, craft()->timezone);
$endDate->modify('+1 day');
$intervalUnit = 'day';
// Prep the query
$query = craft()->db->createCommand()->from('users users')->select('COUNT(*) as value');
if ($userGroupId) {
$query->join('usergroups_users userGroupUsers', 'userGroupUsers.userId = users.id');
$query->where('userGroupUsers.groupId = :userGroupId', array(':userGroupId' => $userGroupId));
}
// Get the chart data table
$dataTable = ChartHelper::getRunChartDataFromQuery($query, $startDate, $endDate, 'users.dateCreated', array('intervalUnit' => $intervalUnit, 'valueLabel' => Craft::t('New Users')));
// Get the total number of new users
$total = 0;
foreach ($dataTable['rows'] as $row) {
$total = $total + $row[1];
}
// Return everything
$this->returnJson(array('dataTable' => $dataTable, 'total' => $total, 'formats' => ChartHelper::getFormats(), 'orientation' => craft()->locale->getOrientation(), 'scale' => $intervalUnit));
}
示例3: savePlainMeta
public function savePlainMeta(BaseFieldType $fieldType)
{
$handle = $fieldType->model->handle;
$elementId = $fieldType->element->id;
$content = $fieldType->element->getContent();
$attr = $content->getAttribute($handle);
if (!$attr) {
return false;
}
$plainMetaRecord = PlainMeta_PlainMetaRecord::model()->findByAttributes(array('elementId' => $elementId, 'handle' => $handle));
if (!$plainMetaRecord) {
$plainMetaRecord = new PlainMeta_PlainMetaRecord();
$attr['elementId'] = $elementId;
$attr['handle'] = $handle;
}
/* Assets */
$assetFields = array('socialOGImageId', 'socialTwitterGalleryImagesId', 'socialTwitterPhotoId', 'socialTwitterProductImageId', 'socialTwitterSummaryImageId', 'socialTwitterSummaryLargeImageId');
foreach ($assetFields as $field) {
$attr[$field] = !empty($attr[$field]) ? $attr[$field][0] : null;
}
/* DateTime */
$dateFields = array();
foreach ($dateFields as $field) {
$attr[$field] = ($date = $attr[$field]) ? DateTime::createFromString($date, craft()->timezone) : null;
}
/* Set Attributes */
$plainMetaRecord->setAttributes($attr, false);
return $plainMetaRecord->save();
}
示例4: toIso8601
/**
* Converts a date to an ISO-8601 string.
*
* @param mixed $date The date, in any format that {@link toDateTime()} supports.
*
* @return string|false The date formatted as an ISO-8601 string, or `false` if $date was not a valid date
*/
public static function toIso8601($date)
{
$date = DateTime::createFromString($date);
if ($date) {
return $date->format(\DateTime::ATOM);
} else {
return false;
}
}
示例5: prepValue
public function prepValue($value)
{
$dates = array();
@($dates = json_decode($value));
$dd = array();
if (is_array($dates)) {
foreach ($dates as $date) {
$dd[] = $date == null ? null : DateTime::createFromString($date, craft()->getTimeZone());
}
}
$out_value = array('json' => $value, 'dates' => $dd);
return $out_value;
}
示例6: _convertTimes
/**
* Loops through the data and converts the times to DateTime objects.
*
* @access private
* @param array &$value
*/
private function _convertTimes(&$value, $timezone = null)
{
if (is_array($value)) {
foreach ($value as &$day) {
if (is_string($day['open']) && $day['open'] || is_array($day['open']) && $day['open']['time']) {
$day['open'] = DateTime::createFromString($day['open'], $timezone);
} else {
$day['open'] = '';
}
if (is_string($day['close']) && $day['close'] || is_array($day['close']) && $day['close']['time']) {
$day['close'] = DateTime::createFromString($day['close'], $timezone);
} else {
$day['close'] = '';
}
}
}
}
示例7: actionSaveAnnouncement
/**
* Saves a new or existing announcement.
*
* @return null
*/
public function actionSaveAnnouncement()
{
$this->requirePostRequest();
$announcement = new Maintenance_AnnouncementModel();
$announcement->id = craft()->request->getPost('id');
$announcement->message = craft()->request->getPost('message');
$announcement->startDate = ($startDate = craft()->request->getPost('startDate')) ? DateTime::createFromString($startDate, craft()->timezone) : null;
$announcement->endDate = ($endDate = craft()->request->getPost('endDate')) ? DateTime::createFromString($endDate, craft()->timezone) : null;
$announcement->blockCp = (bool) craft()->request->getPost('blockCp');
$announcement->blockSite = (bool) craft()->request->getPost('blockSite');
if (craft()->maintenance->saveAnnouncement($announcement)) {
craft()->userSession->setNotice(Craft::t('Announcement saved.'));
$this->redirectToPostedUrl();
} else {
craft()->userSession->setError(Craft::t('Couldn’t save announcement.'));
}
// Send the announcement back to the template
craft()->urlManager->setRouteVariables(array('announcement' => $announcement));
}
示例8: runStep
/**
* Runs a task step.
*
* @param int $step
* @return bool
*/
public function runStep($step)
{
try {
$element = $this->_elements[$step];
$query = craft()->db->createCommand()->select('venti.eventid,venti.startDate,venti.endDate,venti.allDay,venti.repeat,venti.rRule,venti.summary,venti.isrepeat')->from('venti_events venti');
$query->andWhere(array("venti.eventid" => $element->id));
$query->andWhere("venti.isrepeat is NULL");
$attributes = $query->queryAll();
$attributes[0]['startDate'] = DateTime::createFromString($attributes[0]['startDate'], null, true);
$attributes[0]['endDate'] = DateTime::createFromString($attributes[0]['endDate'], null, true);
if (craft()->venti_eventManage->saveEventData($element, $attributes[0])) {
return true;
} else {
VentiPlugin::log('Recurring event with ID ' . $element->id . " was not saved.", LogLevel::Error);
return 'Recurring event with ID ' . $element->id . " was not saved.";
}
} catch (Exception $e) {
VentiPlugin::log('An exception was thrown while trying to save the recurring event with the ID “' . $this->_elementIds[$step] . '”: ' . $e->getMessage(), LogLevel::Error);
return 'An exception was thrown while trying to save the recurring event with the ID “' . $this->_elementIds[$step] . '”: ' . $e->getMessage();
}
}
示例9: actionGetStatsData
/**
* Returns the data needed to display a stats chart.
*/
public function actionGetStatsData()
{
$statHandle = craft()->request->getRequiredPost('statHandle');
$startDateParam = craft()->request->getRequiredPost('startDate');
$endDateParam = craft()->request->getRequiredPost('endDate');
$stat = craft()->elementStats_stats->getStatByHandle($statHandle);
if (!$stat) {
$this->returnErrorJson(Craft::t('Could not find the selected stat.'));
}
if (!$stat->elementType || !$stat->dateColumn) {
$this->returnErrorJson(Craft::t('The stat does not support chart view.'));
}
// Prep the query
try {
$criteria = $stat->getCriteria();
} catch (\Exception $e) {
ElementStatsPlugin::log('There was an error while generating the stats. ' . $e->getMessage(), LogLevel::Error);
$this->returnErrorJson(Craft::t('There was an error while generating the stats.'));
}
$query = craft()->elements->buildElementsQuery($criteria);
$query->select('COUNT(*) as value');
// Query debugging
// ElementStatsPlugin::log(print_r($query->getText(), true), LogLevel::Info, true);
// Prep the dates
$startDate = DateTime::createFromString($startDateParam, craft()->timezone);
$endDate = DateTime::createFromString($endDateParam, craft()->timezone);
$endDate->modify('+1 day');
$intervalUnit = 'day';
// Get the chart data table
$dataTable = ChartHelper::getRunChartDataFromQuery($query, $startDate, $endDate, $stat->dateColumn, ['intervalUnit' => $intervalUnit, 'valueLabel' => Craft::t('Value')]);
// Get the total number of elements
$total = 0;
foreach ($dataTable['rows'] as $row) {
$total = $total + $row[1];
}
// Return everything
$this->returnJson(['dataTable' => $dataTable, 'total' => $total, 'formats' => ChartHelper::getFormats(), 'orientation' => craft()->locale->getOrientation(), 'scale' => $intervalUnit]);
}
示例10: prepForElementModel
public function prepForElementModel(&$fields, EntryModel $element)
{
// Set author
$author = FeedMe_Element::Author;
if (isset($fields[$author])) {
$user = craft()->users->getUserByUsernameOrEmail($fields[$author]);
$element->{$author} = is_numeric($fields[$author]) ? $fields[$author] : ($user ? $user->id : 1);
//unset($fields[$author]);
} else {
$user = craft()->userSession->getUser();
$element->{$author} = $element->{$author} ? $element->{$author} : ($user ? $user->id : 1);
}
// Set slug
$slug = FeedMe_Element::Slug;
if (isset($fields[$slug])) {
$element->{$slug} = ElementHelper::createSlug($fields[$slug]);
//unset($fields[$slug]);
}
// Set postdate
$postDate = FeedMe_Element::PostDate;
if (isset($fields[$postDate])) {
$d = date_parse($fields[$postDate]);
$date_string = date('Y-m-d H:i:s', mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'], $d['year']));
$element->{$postDate} = DateTime::createFromString($date_string, craft()->timezone);
//unset($fields[$postDate]);
}
// Set expiry date
$expiryDate = FeedMe_Element::ExpiryDate;
if (isset($fields[$expiryDate])) {
$d = date_parse($fields[$expiryDate]);
$date_string = date('Y-m-d H:i:s', mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'], $d['year']));
$element->{$expiryDate} = DateTime::createFromString($date_string, craft()->timezone);
//unset($fields[$expiryDate]);
}
// Set enabled
$enabled = FeedMe_Element::Enabled;
if (isset($fields[$enabled])) {
$element->{$enabled} = (bool) $fields[$enabled];
//unset($fields[$enabled]);
}
// Set title
$title = FeedMe_Element::Title;
if (isset($fields[$title])) {
$element->getContent()->{$title} = $fields[$title];
//unset($fields[$title]);
}
// Set parent or ancestors
$parent = FeedMe_Element::Parent;
$ancestors = FeedMe_Element::Ancestors;
if (isset($fields[$parent])) {
$data = $fields[$parent];
// Don't connect empty fields
if (!empty($data)) {
// Find matching element
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->sectionId = $element->sectionId;
$criteria->search = '"' . $data . '"';
// Return the first found element for connecting
if ($criteria->total()) {
$element->{$parent} = $criteria->first()->id;
}
}
//unset($fields[$parent]);
} elseif (isset($fields[$ancestors])) {
$data = $fields[$ancestors];
// Don't connect empty fields
if (!empty($data)) {
// Get section data
$section = new SectionModel();
$section->id = $element->sectionId;
// This we append before the slugified path
$sectionUrl = str_replace('{slug}', '', $section->getUrlFormat());
// Find matching element by URI (dirty, not all structures have URI's)
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->sectionId = $element->sectionId;
$criteria->uri = $sectionUrl . craft()->feedMe->slugify($data);
$criteria->limit = 1;
// Return the first found element for connecting
if ($criteria->total()) {
$element->{$parent} = $criteria->first()->id;
}
}
//unset($fields[$ancestors]);
}
// Return element
return $element;
}
示例11: parseDateParam
/**
* Parses a date param value to a DbCommand where condition.
*
* @param string $key
* @param string $operator
* @param string|array|DateTime $dates
* @param array &$params
* @return mixed
*/
public static function parseDateParam($key, $operator, $dates, &$params)
{
$conditions = array();
$dates = ArrayHelper::stringToArray($dates);
foreach ($dates as $date) {
if (!$date instanceof \DateTime) {
$date = DateTime::createFromString($date, Craft::getTimezone());
}
$param = ':p' . StringHelper::randomString(9);
$params[$param] = DateTimeHelper::formatTimeForDb($date->getTimestamp());
$conditions[] = $key . $operator . $param;
}
if (count($conditions) == 1) {
return $conditions[0];
} else {
array_unshift($conditions, 'or');
return $conditions;
}
}
示例12: _populateEntryModel
/**
* Populates an EntryModel with post data.
*
* @param EntryModel $entry
*
* @return null
*/
private function _populateEntryModel(EntryModel $entry)
{
// Set the entry attributes, defaulting to the existing values for whatever is missing from the post data
$entry->typeId = craft()->request->getPost('typeId', $entry->typeId);
$entry->authorId = craft()->request->getPost('author', $entry->authorId ? $entry->authorId : craft()->userSession->getUser()->id);
$entry->slug = craft()->request->getPost('slug', $entry->slug);
$entry->postDate = ($postDate = craft()->request->getPost('postDate')) ? DateTime::createFromString($postDate, craft()->timezone) : $entry->postDate;
$entry->expiryDate = ($expiryDate = craft()->request->getPost('expiryDate')) ? DateTime::createFromString($expiryDate, craft()->timezone) : null;
$entry->enabled = (bool) craft()->request->getPost('enabled', $entry->enabled);
$entry->localeEnabled = (bool) craft()->request->getPost('localeEnabled', $entry->localeEnabled);
$entry->getContent()->title = craft()->request->getPost('title', $entry->title);
$fieldsLocation = craft()->request->getParam('fieldsLocation', 'fields');
$entry->setContentFromPost($fieldsLocation);
$entry->parentId = craft()->request->getPost('parentId');
$entry->revisionNotes = craft()->request->getPost('revisionNotes');
}
示例13: checkPluginReleaseFeeds
/**
* Check plugins’ release feeds and include any pending updates in the given UpdateModel
*
* @param UpdateModel $updateModel
*/
public function checkPluginReleaseFeeds(UpdateModel $updateModel)
{
$userAgent = 'Craft/' . craft()->getVersion() . '.' . craft()->getBuild();
foreach ($updateModel->plugins as $pluginUpdateModel) {
// Only check plugins where the update status isn't already known from the ET response
if ($pluginUpdateModel->status != PluginUpdateStatus::Unknown) {
continue;
}
// Get the plugin and its feed URL
$plugin = craft()->plugins->getPlugin($pluginUpdateModel->class);
$feedUrl = $plugin->getReleaseFeedUrl();
// Skip if the plugin doesn't have a feed URL
if ($feedUrl === null) {
continue;
}
// Make sure it's HTTPS
if (strncmp($feedUrl, 'https://', 8) !== 0) {
Craft::log('The “' . $plugin->getName() . '” plugin has a release feed URL, but it doesn’t begin with https://, so it’s getting skipped (' . $feedUrl . ').', LogLevel::Warning);
continue;
}
try {
// Fetch it
$client = new \Guzzle\Http\Client();
$client->setUserAgent($userAgent, true);
$options = array('timeout' => 5, 'connect_timeout' => 2, 'allow_redirects' => true, 'verify' => false);
$request = $client->get($feedUrl, null, $options);
// Potentially long-running request, so close session to prevent session blocking on subsequent requests.
craft()->session->close();
$response = $request->send();
if (!$response->isSuccessful()) {
Craft::log('Error in calling ' . $feedUrl . '. Response: ' . $response->getBody(), LogLevel::Warning);
continue;
}
$responseBody = $response->getBody();
$releases = JsonHelper::decode($responseBody);
if (!$releases) {
Craft::log('The “' . $plugin->getName() . "” plugin release feed didn’t come back as valid JSON:\n" . $responseBody, LogLevel::Warning);
continue;
}
$releaseModels = array();
$releaseTimestamps = array();
foreach ($releases as $release) {
// Validate ite info
$errors = array();
// Any missing required attributes?
$missingAttributes = array();
foreach (array('version', 'downloadUrl', 'date', 'notes') as $attribute) {
if (empty($release[$attribute])) {
$missingAttributes[] = $attribute;
}
}
if ($missingAttributes) {
$errors[] = 'Missing required attributes (' . implode(', ', $missingAttributes) . ')';
}
// Invalid URL?
if (strncmp($release['downloadUrl'], 'https://', 8) !== 0) {
$errors[] = 'Download URL doesn’t begin with https:// (' . $release['downloadUrl'] . ')';
}
// Invalid date?
$date = DateTime::createFromString($release['date']);
if (!$date) {
$errors[] = 'Invalid date (' . $release['date'] . ')';
}
// Validation complete. Were there any errors?
if ($errors) {
Craft::log('A “' . $plugin->getName() . "” release was skipped because it is invalid:\n - " . implode("\n - ", $errors), LogLevel::Warning);
continue;
}
// All good! Let's make sure it's a pending update
if (!version_compare($release['version'], $plugin->getVersion(), '>')) {
continue;
}
// Create the release note HTML
if (!is_array($release['notes'])) {
$release['notes'] = array_filter(preg_split('/[\\r\\n]+/', $release['notes']));
}
$notes = '';
$inList = false;
foreach ($release['notes'] as $line) {
// Escape any HTML
$line = htmlspecialchars($line, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
// Is this a heading?
if (preg_match('/^#\\s+(.+)/', $line, $match)) {
if ($inList) {
$notes .= "</ul>\n";
$inList = false;
}
$notes .= '<h3>' . $match[1] . "</h3>\n";
} else {
if (!$inList) {
$notes .= "<ul>\n";
$inList = true;
}
if (preg_match('/^\\[(\\w+)\\]\\s+(.+)/', $line, $match)) {
$class = strtolower($match[1]);
//.........这里部分代码省略.........
示例14: parseDateParam
/**
* Normalizes date params and then sends them off to parseParam().
*
* @param string $column
* @param string|array|DateTime $value
* @param array &$params
*
* @return mixed
*/
public static function parseDateParam($column, $value, &$params)
{
$normalizedValues = array();
$value = ArrayHelper::stringToArray($value);
if (!count($value)) {
return '';
}
if ($value[0] == 'and' || $value[0] == 'or') {
$normalizedValues[] = $value[0];
array_shift($value);
}
foreach ($value as $val) {
// Is this an empty value?
static::_normalizeEmptyValue($val);
if ($val == ':empty:' || $val == 'not :empty:') {
$normalizedValues[] = $val;
// Sneak out early
continue;
}
if (is_string($val)) {
$operator = static::_parseParamOperator($val);
} else {
$operator = '=';
}
if (!$val instanceof \DateTime) {
$val = DateTime::createFromString($val, craft()->getTimeZone());
}
$normalizedValues[] = $operator . DateTimeHelper::formatTimeForDb($val->getTimestamp());
}
return static::parseParam($column, $normalizedValues, $params);
}
示例15: _setDraftAttributesFromPost
/**
* Sets a draft's attributes from the post data.
*
* @param EntryDraftModel $draft
*
* @return null
*/
private function _setDraftAttributesFromPost(EntryDraftModel $draft)
{
$draft->typeId = craft()->request->getPost('typeId');
$draft->slug = craft()->request->getPost('slug');
$draft->postDate = ($postDate = craft()->request->getPost('postDate')) ? DateTime::createFromString($postDate, craft()->timezone) : $draft->postDate;
$draft->expiryDate = ($expiryDate = craft()->request->getPost('expiryDate')) ? DateTime::createFromString($expiryDate, craft()->timezone) : null;
$draft->enabled = (bool) craft()->request->getPost('enabled');
$draft->getContent()->title = craft()->request->getPost('title');
// Author
$authorId = craft()->request->getPost('author', $draft->authorId ? $draft->authorId : craft()->userSession->getUser()->id);
if (is_array($authorId)) {
$authorId = isset($authorId[0]) ? $authorId[0] : null;
}
$draft->authorId = $authorId;
// Parent
$parentId = craft()->request->getPost('parentId');
if (is_array($parentId)) {
$parentId = isset($parentId[0]) ? $parentId[0] : null;
}
$draft->parentId = $parentId;
}