如何将来自Web Service的Date值转换为PHP中的日期字符串? [重复]

如何将来自Web Service的Date值转换为PHP中的日期字符串?  [重复]

问题描述:

This question already has an answer here:

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 System.Web.Script.Serialization.JavaScriptSerializer class. I have a date field which is turned into a long integer between the paranthesis.

...,"startDate":"\/Date(1387231200000)\/",...

When I try to convert this value to date string using gmdate() function,

$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.

</div>

此问题已经存在 这里有一个答案: p>

  • PHP脚本中的日期时间 3 answers span> li> \ r ul> div>

    我使用我编写的Web服务从MSSQL服务器查询一些数据。 我以JSON格式获取值。 为了将数据表转换为json字符串,我使用 System.Web.Script.Serialization.JavaScriptSerializer code>类。 我有一个日期字段,它在paranthesis之间变成一个长整数。 p>

      ...,“startDate”:“\ / Date(1387231200000)\ /”,.  .. 
      code>  pre> 
     
     

    当我尝试使用 gmdate() code>函数将此值转换为日期字符串时, p>

      $ sDate = gmdate(“d / m / Y”,preg_replace('/ \ D /','',$ jsonArray ['startDate'])); 
      code>  pre  > 
     
     

    我得到 18/08/1968 strong>结果。 但是DB中的实际值是 17.12.2013 00:00:00 strong>。 p>

    我也尝试了 p>

      $ sDate = gmdate(“d / m / Y”,“1387231200000”);  
      code>  pre> 
     
     

    仍然会返回 18/08/1968 strong>。 p> div>

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;
}