zkanoca zkanoca - 2 years ago 70
PHP Question

How to convert Date value coming from Web Service to date string in PHP?

I am querying some data from MSSQL server using a web service which I have written. I get the values in JSON format. In order to convert data table to json string I use

class. I have a date field which is turned into a long integer between the paranthesis.


When I try to convert this value to date string using

$sDate = gmdate("d/m/Y", preg_replace('/\D/','',$jsonArray['startDate']));

I get 18/08/1968 result. But the actual value in DB is 17.12.2013 00:00:00.

I also tried

$sDate = gmdate("d/m/Y", "1387231200000");

still returns 18/08/1968.

Answer Source

Finally I have foundt the solution. According to answer here which was deleted I could have got nearly correct value. As RiggsFolly mentioned, date string closes to desired value after deleted last three zeros.

Then I have changed the time zone to Europe/Istanbul.

$sDate = createDate($jsonArray['startDate']);

And the function createDate() comes:

function createDate($date) {

    $date = preg_replace('/\D/', '', substr($date, 0, -5));

    $desiredDateFormatString = "d/m/Y";

    $inputEpoch = preg_replace('/\D/', '', $date);

    $desiredTimeZoneString = 'Europe/Istanbul';

    $dateTimeObject = new DateTime(date('d.m.Y H:i:s', $inputEpoch));

    $dateTimeObject->setTimezone(new DateTimeZone($desiredTimeZoneString));  

    $outputDateTimeString = $dateTimeObject->format($desiredDateFormatString);

    return $outputDateTimeString;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download