Convert DateTime to String PHP

后端 未结 6 1897
醉梦人生
醉梦人生 2020-11-30 18:27

I have already researched a lot of site on how can I convert PHP DateTime object to String. I always see \"String to DateTime\" and not \"DateTime to String\"

PHP D

相关标签:
6条回答
  • 2020-11-30 18:45
    echo date_format($date,"Y/m/d H:i:s");
    
    0 讨论(0)
  • 2020-11-30 18:46

    Shorter way using list. And you can do what you want with each date component.

    list($day,$month,$year,$hour,$min,$sec) = explode("/",date('d/m/Y/h/i/s'));
    echo $month.'/'.$day.'/'.$year.' '.$hour.':'.$min.':'.$sec;
    
    0 讨论(0)
  • 2020-11-30 18:48

    The simplest way I found is:

    $date   = new DateTime(); //this returns the current date time
    $result = $date->format('Y-m-d-H-i-s');
    echo $result . "<br>";
    $krr    = explode('-', $result);
    $result = implode("", $krr);
    echo $result;
    

    I hope it helps.

    0 讨论(0)
  • 2020-11-30 18:54

    You can use the format method of the DateTime class:

    $date = new DateTime('2000-01-01');
    $result = $date->format('Y-m-d H:i:s');
    

    If format fails for some reason, it will return FALSE. In some applications, it might make sense to handle the failing case:

    if ($result) {
      echo $result;
    } else { // format failed
      echo "Unknown Time";
    }
    
    0 讨论(0)
  • 2020-11-30 18:59

    Its worked for me

    $start_time   = date_create_from_format('Y-m-d H:i:s', $start_time);
    $current_date = new DateTime();
    $diff         = $start_time->diff($current_date);
    $aa           = (string)$diff->format('%R%a');
    echo gettype($aa);
    
    0 讨论(0)
  • 2020-11-30 19:01

    There are some predefined formats in date_d.php to use with format like:

    define ('DATE_ATOM', "Y-m-d\TH:i:sP");
    define ('DATE_COOKIE', "l, d-M-y H:i:s T");
    define ('DATE_ISO8601', "Y-m-d\TH:i:sO");
    define ('DATE_RFC822', "D, d M y H:i:s O");
    define ('DATE_RFC850', "l, d-M-y H:i:s T");
    define ('DATE_RFC1036', "D, d M y H:i:s O");
    define ('DATE_RFC1123', "D, d M Y H:i:s O");
    define ('DATE_RFC2822', "D, d M Y H:i:s O");
    define ('DATE_RFC3339', "Y-m-d\TH:i:sP");
    define ('DATE_RSS', "D, d M Y H:i:s O");
    define ('DATE_W3C', "Y-m-d\TH:i:sP");
    

    Use like this:

    $date = new \DateTime();
    $string = $date->format(DATE_RFC2822);
    
    0 讨论(0)
提交回复
热议问题