3

I want to convert jalali to gregorian. In input is taken in the jalali date in view :

<?= $form->field($model, 'start_date')->widget(jDate\DatePicker::className())->textInput() ?>

controller:

 $jstartdate = $model->start_date; // string(10) "1395/06/15" 

Now I want to store in database with gregorian format ("2016-09-05"). Which function in jalali class does this work? I used many function for example createFromFormat or toGregorian. but I did not get result.

ParisaN
  • 1,816
  • 2
  • 23
  • 55

2 Answers2

4

For an easy way, you must have intl extension installed on your server and your php version must be higher that 5.4. If it is, you easily can make an IntlCalendar instance with Persian calendar parameters:

$date = IntlCalendar::createInstance(
    'Asia/Tehran',
    'fa_IR@calendar=persian'
);

set your datetime:

$date->set(1395, 5, 15, 19, 17, 11); // Notice that month number begin from 0 not 1.

then make an instance of IntlDateFormatter with Gregorian calendar -or every calendar you want:

$intlDateFormatter = new IntlDateFormatter(
    "en_US", // string $locale
    IntlDateFormatter::FULL, // int $datetype
    IntlDateFormatter::FULL, // int $timetype
    'Asia/Tehran', // mixed $timezone
    IntlDateFormatter::GREGORIAN, // mixed $calendar
    'yyyy/MM/dd HH:mm:ss' // string $pattern
);

and use toDateTime method of that for showing your desired date:

var_dump($intlDateFormatter->format($date));
// /srv/http/test/DateTime.php:29:
// string(19) "2016/09/05 19:17:11"

P.S.: I write a small library for converting date that can be found here: https://github.com/meysampg/intldate, Also if you only want to represent date on other system, you can use IntlDateBehavior.

meysam
  • 1,754
  • 2
  • 20
  • 30
  • dont work. i tested, 1396/03/31 to 2017-07-22 , it's not correct – user3770797 Jun 21 '17 at 09:25
  • I will check it! Can you open an issue about the bug? It's hard to reproduce with this level of information. @user3770797 – meysam Jun 21 '17 at 10:42
  • The new value for IntlCalendar::FIELD_DAY_OF_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, …, December is 11 and Undecember (if the calendar has it) is 12. https://www.php.net/manual/en/intlcalendar.set.php – MH.Kashizadeh Mar 24 '20 at 07:49
4

Since Yii 2.0.7:

Yii::$app->formatter->locale = 'fa_IR@calendar=persian';
Yii::$app->formatter->calendar = \IntlDateFormatter::TRADITIONAL;
Yii::$app->formatter->timeZone = 'UTC';
$value = 1451606400; // Fri, 01 Jan 2016 00:00:00 (UTC)
echo Yii::$app->formatter->asDate($value, 'php:Y');
// outputs "۱۳۹۴"
Sajjad Dehghani
  • 640
  • 1
  • 6
  • 15