1

i need to convert a date with this format (2017-06-14T08:22:29.296-03:00) to Y-m-d H:i:s. I take that date from an xml response from a soap service, And i need to check if the expiration date is less than the actual date.

I have this and works OK on localhost, but when is uploaded to other server, i have validation problems:

if($wsaa->get_expiration() < date("Y-m-d h:m:i")) {
    if ($wsaa->generar_TA()) {
        echo '<br>Nuevo Ticket de Acceso Generado'; 
    } else {
        echo '<br>No se pudo obtener ticket de acceso'; 
    }
} else {
    echo '<br>TA expira:' . $wsaa->get_expiration(); 
}

$wsaa->get_expiration() return 2017-06-14T08:22:29.296-03:00

I tried to format the date but return with a few minutes of diff.

2 Answers2

4

You can use date function for format and use strtotime to convert current date to timestamp that date function needed:

$datetime = '2017-06-14T08:22:29.296-03:00';

$format_date  = date('Y-m-d H:i:s', strtotime($datetime));
Mohammad Hamedani
  • 3,304
  • 3
  • 10
  • 22
0

An alternative solution in OOP using Carbon from http://carbon.nesbot.com. If you run my example, you might notice that solution1() is an hour behind. That's the reason why I recommend Carbon is that it plays really well with time-zones.

First run "composer require nesbot/carbon";

<?php
require 'vendor/autoload.php';
use Carbon\Carbon;

class FormatDate 
{   
    protected $dateTime;
    protected $newFormat;

    public function __construct($dateTime, $newFormat) 
    {   
        $this->dateTime = $dateTime;
        $this->newFormat = $newFormat;
    }   

    // Solution 1
    public function solution1()
    {   
        $format_date = date($this->newFormat, strtotime($this->dateTime));

        return $format_date;
    }   

    // Solution 2
    public function solution2()
    {   
        $date = Carbon::parse($this->dateTime)->format($this->newFormat);

        return $date;
    }   
}

$datetime = '2017-06-14T08:22:29.296-03:00';
$newFormat = 'Y-m-d H:i:s';

// Solution 1
echo (new FormatDate($datetime, $newFormat))->solution1();

echo '----------------------------';

// Solution 2
echo (new FormatDate($datetime, $newFormat))->solution2();
Ravi Gehlot
  • 1,099
  • 11
  • 17