Convert a date format in PHP

后端 未结 18 2336
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  • 2020-11-21 06:38

    Given below is PHP code to generate tomorrow's date using mktime() and change its format to dd/mm/yyyy format and then print it using echo.

    $tomorrow = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
    echo date("d", $tomorrow) . "/" . date("m", $tomorrow). "/" . date("Y", $tomorrow);
    
    0 讨论(0)
  • 2020-11-21 06:39

    Use this function to convert from any format to any format

    function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
        $date_aux = date_create_from_format($from_format, $date);
        return date_format($date_aux,$to_format);
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 06:41

    Simple way Use strtotime() and date():

    $original_dateTime = "2019-05-11 17:02:07"; #This may be database datetime
    $newDate = date("d-m-Y", strtotime($original_dateTime));
    

    With time

    $newDate = date("d-m-Y h:i:s a", strtotime($original_dateTime));
    
    0 讨论(0)
  • 2020-11-21 06:43

    Use:

    implode('-', array_reverse(explode('-', $date)));
    

    Without the date conversion overhead, I am not sure it'll matter much.

    0 讨论(0)
  • 2020-11-21 06:45
    $timestamp = strtotime(your date variable); 
    $new_date = date('d-m-Y', $timestamp);
    

    For more, see the documentation for strtotime.

    Or even shorter:

    $new_date = date('d-m-Y', strtotime(your date variable));
    
    0 讨论(0)
提交回复
热议问题