I'm trying to show a localized date with strftime but it does not work.
class ExampleController extends AbstractActionController
{
public function indexAction()
{
$openDate = DateTime::createFromFormat(...);
setlocale(LC_ALL, Locale::getDefault());
Debug::dump(Locale::getDefault()); // shows 'fr_FR'
Debug::dump(strftime('%B %Y', $openDate->getTimestamp())); // shows 'August 2013' instead of 'Août 2013'
}
}
In module/Application/config/module.config.php
return array(
...
'translator' => array(
'locale' => 'fr_FR',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
...
);
Is someone can tell me why the month is not translated in French ?
strftime has nothing to do with ZF2 or the intl php extension. However ZF2 does come with a DateFormat view helper that should solve your problem. The full documentation is available at:
http://framework.zend.com/manual/2.2/en/modules/zend.i18n.view.helpers.html#dateformat-helper
A quick example:
Debug::dump($this->dateFormat($openDate->getTimestamp(), IntlDateFormatter::LONG));
The default locale for the DateFormat view helper is that returned by Locale::getDefault() therefore it should return the date in french as you require.
To use your custom format:
Debug::dump($this->dateFormat($openDate->getTimestamp(), IntlDateFormatter::LONG, IntlDateFormatter::LONG, null, "dd LLLL Y - HH:mm"));
According what Tomdarkness said, I found a way to do what I wanted. I used IntlDateFormatter :
$formatter = \IntlDateFormatter::create(
\Locale::getDefault(), // fr_FR
\IntlDateFormatter::FULL,
\IntlDateFormatter::FULL,
'Europe/Paris',
\IntlDateFormatter::GREGORIAN,
'dd LLLL Y - HH:mm'
);
echo $formatter->format($openDate); // shows '20 août 2013 - 14:39'
I think maybe I will code my own dateFormat view helper based on this.
Related
In my DB I store all datetime fields in UTC format. Also, I have the ability to change default time zone by users. Each user can have own time zone, different from UTC.
How shall I display all model datetime fields in this case?
I have an idea. To do this action for each ActiveRecord model:
public function init()
{
parent::init();
$this->on(ActiveRecord::EVENT_AFTER_FIND, function($event) {
$this->created_date = (new \DateTime('now', new \DateTimeZone("Europe/Kiev")))->format("Y-m-d H:i:s");
});
}
But I'm not sure it's the best way for big amount of models...
if the dates are stored in UTC why not append the string UTC along the time and display it
$time = strtotime($this->created_at.' UTC');
date("Y-m-d H:i:s", $time);
Your code will look like this
public function init()
{
parent::init();
$this->on(ActiveRecord::EVENT_AFTER_FIND, function($event) {
$time = strtotime($model->create_at.' UTC');
$this->created_date = date("Y-m-d H:i:s", $time);
});
}
if I would do it I would just create a separate Helper and use it to display the date in the local format rather than EVENT_AFTER_FIND
Another alternative is to use this Extension
Search for frontend/config/main.php
Try putting in
return [
...
'components' => [
...
a FORMATTER part like
'formatter' => [
'dateFormat' => 'dd/MM/yyyy',
'datetimeFormat' => 'dd/MM/yyyy H:i:s',
'timeFormat' => 'H:i:s',
'locale' => 'it-IT',
'decimalSeparator' => ',',
'thousandSeparator' => '.',
'currencyCode' => 'EUR',
'numberFormatterSymbols' => [
NumberFormatter::CURRENCY_SYMBOL => '€',
],
'timeZone' => 'Europe/Rome',
],
Set your parameters like TimeZone, Currency, etc...
NB: I dont remember but maybe the NumberFormatter part need some other setup so delete the numberFormatterSymbols part if it give to you an error
I have a form element in a ZF2 application that uses DateSelect to allow a user to enter their date of birth. Currently the fields are shown in the order d-m-y. I would like to reverse this order so it is displayed as y-m-d. I have come across posts on SO that recommend changing the locale in PHP to change the order but that is not an option for me. I have also tried
$this->add(array(
'type' => 'Zend\Form\Element\DateSelect',
'name' => 'dob',
'options' => array(
'label' => 'Date of Birth',
'create_empty_option' => true,
'pattern' => $this->options['isMobile'] ? 'd MMM y' : 'd MMM y',
'empty_options' => array(
'day' => 'DD',
'month' => 'MM',
'year' => 'YYYY',
),
'allowLabelHTML' => TRUE,
'required' => true,
)
));
$this->get('dob')->setFormat('Y-m-d');
Which was an accepted answer to another SO question but that produces an internal server error for me. I would be surprised if this is not possible, maybe using an helper file but I cannot find anything on the web to suggest how, apart from the above and changing the locale. Can anyone help with this?
You get fatal error because method setFormat() does not exist in Zend\Form\Element\DateSelect.
I don't think it is possible to achieve this without writing own view helper.
Zend\Form\Element\DateSelect is based on locale settings, so you can pass locale short code as parameter to view helper, so order of elements will be proper for provided region.
This view helper takes 3 parameters $this->formDateSelect($element, $intlFormat, $locale), so you use it like this:
echo $this->formDateSelect($form->get('dob'), \IntlDateFormatter::LONG, 'en_Gb');
or...
echo $this->formDateSelect()->setLocale('en_Gb')->render($form->get('dob'));
or... you can change locale settings in your php.ini file
intl.default_locale = en_Gb
I am using datepicker in yii and I want to disable the previous dates on the calendar to avoid picking them.
Here's my code:
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model'=>$model,
'attribute'=>'arrival_date_as_per_recorded_travel',
'name'=>'arrival_date_as_per_recorded_travel',
'value'=>$eta_date_formatted,
// additional javascript options for the date picker plugin
'options'=>array(
'startDate'=>date("yy-mm-dd"),
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
'changeMonth'=>'true',
'changeYear'=>'true',
'yearRange'=>'2013:2100',),
'htmlOptions'=>array(
'id'=>'arrival_date_as_per_recorded_travel',
'style'=>'height:20px;width:150px',
'value'=>$eta_date_formatted,
'onblur'=>'if(this.value=="")this.value=""'
),
));
As for Yii2 (added this as answer as the question is not tagged under yii 1.x)
<?php
use yii\jui\DatePicker;
?>
<?=
DatePicker::widget([
'name' => 'to_date',
'dateFormat' => 'dd/MM/yyyy',
'clientOptions' => [
'minDate' => 0
]
])
?>
change your options with the following code
'options'=>array(
'startDate'=>date("yy-mm-dd"),
'minDate'=>'0', // this will disable previous dates from datepicker
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
'changeMonth'=>'true',
'changeYear'=>'true',
'yearRange'=>'2013:2100',),
'minDate'=>'0' will disable the previous dates...
You can take look of Jquery Date Picker API (minDate)
Hope it may help you...
I have tried previous answers but nothing worked.
Here is how i solved this
The minDate is not found in the documentations https://www.malot.fr/bootstrap-datetimepicker/
There is something like minDate no it's called startDate but it accepts only Date.
startDate Date. Default: Beginning of time The earliest date that may be selected; all earlier dates will be disabled. as in Offical documentations.
So here you go.
<?php
$now = new DateTime();
echo $form->field($data['model'], 'expire_date' ,
['template' =>
'{label}<p class="sub-label">' . \Yii::t("main","After this date people won't be able to bid on this job no more.").'</p> {input}{error}{hint}'])
->widget(DateTimePicker::classname(),
[
'options' => [
'placeholder' => \Yii::t("main","Enter a date..."),
'autoComplete' => 'off',
],
//'convertFormat' => true,
'language' => "Yii::$app->language;",
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd hh:ii:ss',
'startDate' => date_format($now, 'Y-m-d'), //startDate Date. Default: Beginning of time The earliest date that may be selected; all earlier dates will be disabled.
]
]);?>
Adding the following to your options array should help.
minDate: new Date(),
Does anyone know if it is possible to set timezone in the log4php library configuration?
I did not see any information regarding this in the official docs, but log4j has this implemented.
Right now, I am relying on php's *date_default_timezone_set* function to do the trick, but I wanted to leave log4php to handle this on its own... I wonder if there is a to-do list for this or we are supposed to rely on the built-in function by ourselves.
Here is the code I have:
date_default_timezone_set("America/New_York");
require_once (dirname(__FILE__) . '/lib/log4php/Logger.php');
Logger::configure(
array(
'appenders' => array(
'default' => array(
'class' => 'LoggerAppenderRollingFile',
'layout' => array(
'class' => 'LoggerLayoutPattern',
'params' => array(
'conversionPattern' => '%d{Y-m-d H:i:s.u} [%t] %-5p - %m%n'
)
),
'params' => array(
'file' => '/var/log/myapp/myapp.' . date('Y-m-d') . '.log',
'maxFileSize' => '1MB',
'maxBackupIndex' => 10,
),
),
),
'rootLogger' => array(
'appenders' => array('default'),
),
)
);
$logger = Logger::getLogger('myapp');
for( $i=0; $i<5000; $i++ ) {
$logger->info("This is a test [${i}].");
}
In case this code serves someone else with similar issue.
Be safe,
A defined default timezone belongs to a fully working php application.
Apart from that, you are not very clear in stating what you expect log4php to do. The project has everything from mailing list to issue tracker - you are welcome to send your wishes.
I had a similar problem. You can log the date and time for UTC/GMT in the log4php by changing one line of code in the module.
Here is how I did. Go to the module and find the file LoggerPatternConverterDate.php.
cd log4php/pattern/
vim LoggerPatternConverterDate.php
Find the private function date($format, $utimestamp) (Line 84 for me) and change the line of code that returns.
This:
return date(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
Becomes:
return gmdate(preg_replace('`(?<!\\\\)u`', $ms, $format), $timestamp);
Also, find the file: log4php/appenders/LoggerAppenderDailyFile.php and change the following line:
This:
return date($this->datePattern, $timestamp);
Becomes:
return gmdate($this->datePattern, $timestamp);
NOTE: The only thing changed is the function used to format the date string. date() depends on timezone that you set using date_default_timezone_set whereas gmdate() formats the date and time in UTC/GMT irrespective of default timezone.
When using Date field in forms with Symfony2, they are displayed in three different select boxes.
Something like :
dd/mm/YYYY
What we would like to do is display the months in text January, February.... instead of 1,2,3...
How to force display in full text for the months dropdown ?
EDIT : Here is the code I use in my form class :
$builder->add('dateOfBirth', 'birthday', array(
'format' => 'dd - MM - yyyy',
'widget' => 'choice',
'years' => range(date('Y'), date('Y')-70)
));
EDIT2 : Image showing F
Look at the code of the DateType class, it has a format option:
$allowedFormatOptionValues = array(
\IntlDateFormatter::FULL,
\IntlDateFormatter::LONG,
\IntlDateFormatter::MEDIUM,
\IntlDateFormatter::SHORT,
);
// If $format is not in the allowed options, it's considered as the pattern of the formatter if it is a string
if (!in_array($format, $allowedFormatOptionValues, true)) {
if (is_string($format)) {
$defaultOptions = $this->getDefaultOptions($options);
$format = $defaultOptions['format'];
$pattern = $options['format'];
} else {
throw new CreationException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom pattern');
}
}
$formatter = new \IntlDateFormatter(
\Locale::getDefault(),
$format,
\IntlDateFormatter::NONE,
\DateTimeZone::UTC,
\IntlDateFormatter::GREGORIAN,
$pattern
);
UPDATE
$builder->add('dateOfBirth', 'birthday', array(
'format' => 'dd - MMMM - yyyy',
'widget' => 'choice',
'years' => range(date('Y'), date('Y')-70)
));