Convert a date format in PHP

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

    There are two ways to implement this:

    1.

        $date = strtotime(date);
        $new_date = date('d-m-Y', $date);
    

    2.

        $cls_date = new DateTime($date);
        echo $cls_date->format('d-m-Y');
    
    0 讨论(0)
  • 2020-11-21 06:30
    date('m/d/Y h:i:s a',strtotime($val['EventDateTime']));
    
    0 讨论(0)
  • 2020-11-21 06:33

    You can try the strftime() function. Simple example: strftime($time, '%d %m %Y');

    0 讨论(0)
  • 2020-11-21 06:34

    In PHP any date can be converted into the required date format using different scenarios for example to change any date format into Day, Date Month Year

    $newdate = date("D, d M Y", strtotime($date));
    

    It will show date in the following very well format

    Mon, 16 Nov 2020

    0 讨论(0)
  • 2020-11-21 06:36

    If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,

    $myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
    $newDateString = $myDateTime->format('d-m-Y');
    

    Or, equivalently:

    $newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');
    

    You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.

    Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:

    <?php
        $source = '2012-07-31';
        $date = new DateTime($source);
        echo $date->format('d.m.Y'); // 31.07.2012
        echo $date->format('d-m-Y'); // 31-07-2012
    ?>
    
    0 讨论(0)
  • 2020-11-21 06:37

    Use strtotime() and date():

    $originalDate = "2010-03-21";
    $newDate = date("d-m-Y", strtotime($originalDate));
    

    (See the strtotime and date documentation on the PHP site.)

    Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTime class to parse and format :-)

    0 讨论(0)
提交回复
热议问题