Home > OS >  Php function to return only the date from a DateTime format
Php function to return only the date from a DateTime format

Time:03-16

I have a string with the DateTime format '2022-03-17T15:00:00 02:00' and I need a php function to return only the Date '2022-03-17'. I didn't find a solution. The string '2022-03-17T15:00:00 02:00' is variable in the xml feed. It change every day, so it must formatted to included in the function.

CodePudding user response:

I'm pretty sure I've seen this problem a lot of time already. Do some proper search but in the meantime. Use this:

$date = '2022-03-17T15:00:00 02:00';
var_dump(date('Y-m-d',strtotime($date))); //output: 2022-03-17

CodePudding user response:

store your date time in a variable and try this:

$date_to_be_formatted = '2022-03-17T15:00:00 02:00';
echo get_date($date_to_be_formatted);

function get_date($data_to_be_formatted){
    $formatted_date = date('Y-m-d',strtotime($date));
    return $formatted_date;
  }
    
    output:
    2022-03-17

CodePudding user response:

strtotime is not suitable in conjunction with date to convert a date that contains a time zone such as 02:00 here. Errors may occur in connection with other time zones. Example:

date_default_timezone_set('America/New_York');

$time = '2022-03-17T01:00:00 02:00';
echo date("Y-m-d", strtotime($time)); 
//2022-03-16

See for yourself!

The use of DateTime is generally recommended here, since the time zones are handled correctly.

date_default_timezone_set('America/New_York');

$time = '2022-03-17T01:00:00 02:00';
echo date_create($time)->format('Y-m-d'); 
//2022-03-17

CodePudding user response:

echo date("Y-m-d", strtotime($time));

https://www.php.net/manual/en/function.date.php

CodePudding user response:

@Denis and @Relcode

That function now working properly:

function get_date( $time ) {
$time = '2022-03-17T15:00:00 02:00';
echo date("Y-m-d", strtotime($time)); 
}

echo get_date('2022-03-17T15:00:00 02:00');

Output: 2022-03-17

  • Related