Convert a date format in PHP

后端 未结 18 2408
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 06:09

I am trying to convert a date from yyyy-mm-dd to dd-mm-yyyy (but not in SQL); however I don\'t know how the date function requires a timestamp, and

18条回答
  •  猫巷女王i
    2020-11-21 06:40

    function dateFormat($date)
    {
        $m = preg_replace('/[^0-9]/', '', $date);
        if (preg_match_all('/\d{2}+/', $m, $r)) {
            $r = reset($r);
            if (count($r) == 4) {
                if ($r[2] <= 12 && $r[3] <= 31) return "$r[0]$r[1]-$r[2]-$r[3]"; // Y-m-d
                if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$r[2]$r[3]-$r[1]-$r[0]"; // d-m-Y
                if ($r[0] <= 12 && $r[1] <= 31) return "$r[2]$r[3]-$r[0]-$r[1]"; // m-d-Y
                if ($r[2] <= 31 && $r[3] <= 12) return "$r[0]$r[1]-$r[3]-$r[2]"; //Y-m-d
            }
    
            $y = $r[2] >= 0 && $r[2] <= date('y') ? date('y') . $r[2] : (date('y') - 1) . $r[2];
            if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$y-$r[1]-$r[0]"; // d-m-y
        }
    }
    
    var_dump(dateFormat('31/01/00')); // return 2000-01-31
    var_dump(dateFormat('31/01/2000')); // return 2000-01-31
    var_dump(dateFormat('01-31-2000')); // return 2000-01-31
    var_dump(dateFormat('2000-31-01')); // return 2000-01-31
    var_dump(dateFormat('20003101')); // return 2000-01-31
    

提交回复
热议问题