Convert a date format in PHP

后端 未结 18 2348
爱一瞬间的悲伤
爱一瞬间的悲伤 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:49

    Note: Because this post's answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I'm only keeping it here for historical purposes.

    Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it's in ISO format date "YYYY-MM-DD".

    Also, even though my Date_Converter function might still work, I'd like to warn that there may be imprecise statements below, so please do disregard them.

    The most voted answer is actually incorrect!

    The PHP strtotime manual here states that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".

    That means that a date provided as "Y-m-d" may get misinterpreted by strtotime. You should provide the date in the expected format.

    I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.

    function Date_Converter($date, $locale = "br") {
    
        # Exception
        if (is_null($date))
            $date = date("m/d/Y H:i:s");
    
        # Let's go ahead and get a string date in case we've
        # been given a Unix Time Stamp
        if ($locale == "unix")
            $date = date("m/d/Y H:i:s", $date);
    
        # Separate Date from Time
        $date = explode(" ", $date);
    
        if ($locale == "br") {
            # Separate d/m/Y from Date
            $date[0] = explode("/", $date[0]);
            # Rearrange Date into m/d/Y
            $date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
        }
    
        # Return date in all formats
            # US
            $Return["datetime"]["us"] = implode(" ", $date);
            $Return["date"]["us"]     = $date[0];
    
            # Universal
            $Return["time"]           = $date[1];
            $Return["unix_datetime"]  = strtotime($Return["datetime"]["us"]);
            $Return["unix_date"]      = strtotime($Return["date"]["us"]);
            $Return["getdate"]        = getdate($Return["unix_datetime"]);
    
            # BR
            $Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
            $Return["date"]["br"]     = date("d/m/Y", $Return["unix_date"]);
    
        # Return
        return $Return;
    
    } # End Function
    

提交回复
热议问题