Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Jalali calendar to Gregorian by PHP in CodeIgniter

I need to store Date in Persian (Jalali) date in MySQL. I'm using CodeIgniter. I need something like this:

$Date = Jalali_to_Georgian(1393,5,28) // Output: "2014/08/19"

Do I need to create a new library for this?

like image 580
rostamiani Avatar asked May 04 '15 05:05

rostamiani


2 Answers

It's generally better to stick to existing libs rather than writing your own one. Try, for example, jDateTime or Gregorian-Jalali-Date-Convertor.

P.S. I never tried to use them myself, but first one looks much more solid.

like image 145
borisano Avatar answered Nov 15 '22 17:11

borisano


You can use this function

jalali_to_gregorian($year, $month, $day, $separator);
  • Example with separator:

    jalali_to_gregorian(1398, 5, 7, "-"); // Output => 2019-7-29
    
  • Example without separator:

    jalali_to_gregorian(1398, 5, 7); // Output => ["2019","7","29"]
    

And this is the function:

function jalali_to_gregorian($jy, $jm, $jd, $mod = '')
{
    if ($jy > 979) {
        $gy = 1600;
        $jy -= 979;
    } else {
        $gy = 621;
    }

    $days = (365 * $jy) + (((int)($jy / 33)) * 8) + ((int)((($jy % 33) + 3) / 4)) + 78 + $jd + (($jm < 7) ? ($jm - 1) * 31 : (($jm - 7) * 30) + 186);
    $gy += 400 * ((int)($days / 146097));
    $days %= 146097;
    if ($days > 36524) {
        $gy += 100 * ((int)(--$days / 36524));
        $days %= 36524;
        if ($days >= 365) $days++;
    }
    $gy += 4 * ((int)(($days) / 1461));
    $days %= 1461;
    $gy += (int)(($days - 1) / 365);
    if ($days > 365) $days = ($days - 1) % 365;
    $gd = $days + 1;
    foreach (array(0, 31, ((($gy % 4 == 0) and ($gy % 100 != 0)) or ($gy % 400 == 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) as $gm => $v) {
        if ($gd <= $v) break;
        $gd -= $v;
    }

    return ($mod === '') ? array($gy, $gm, $gd) : $gy . $mod . $gm . $mod . $gd;
}
like image 3
Mahdi Bashirpour Avatar answered Nov 15 '22 17:11

Mahdi Bashirpour