2012-11-13 76 views
1

我正在用這個圈子繞圈!我做了以下內容:在PHP中使用MSSQL datetime時遇到問題(通過SQLSRV)

  1. 檢索從MSSQL日期時間字段的日期通過SQL/PHP
  2. 通過查詢字符串
  3. 發送日期到一個新的PHP頁面嘗試使用該日期在新SQL查詢

我在這裏遇到問題。

如果我使用的回聲:

echo $_REQUEST['rSessionDate']; 
output: 15/10/2012 

這很好,但是當我在一個SQL查詢中使用它,我沒有得到我期望的結果,所以我認爲這樣做將是最好的事情確保它首先被確認爲日期。

如果我使用DATE_FORMAT():

echo date_format($_REQUEST['rSessionDate'],'Y-m-d'); 
output: Warning: date_format() expects parameter 1 to be DateTime, string given in ... 

如果我使用的strtotime():

echo strtotime($_REQUEST['rSessionDate']); 
output: (nothing) 

如果我使用日期():

echo date('Y-m-d H:i',$_REQUEST['rSessionDate']); 
output: Notice: A non well formed numeric value encountered in ... 

如果我使用日期()與strtotime():

echo date('Y-m-d H:i',strtotime($_REQUEST['rSessionDate'])); 
output: 1970-01-01 01:00 

我確定我完全錯過了一些簡單的東西。

編輯:我已經嘗試了一些新的功能,我發現:

SELECT fCourseCode ,fCourseTitle FROM tCourses WHERE fCourseCode = '4B' AND (ISNULL(fValidStart, 0) <= CAST('2012-10-15 00:00:00' as DATETIME)) 
:我一直在使用CAST試圖

$rSessionDate = new DateTime($_REQUEST['rSessionDate']); 
echo $rSessionDate->format('Y-m-d H:i:s'); 
output: Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (15/10/2012) at position 0 (1): Unexpected character' 

和:

$rSessionDate = date_create($_REQUEST['rSessionDate']); 
echo date_format($rSessionDate, 'Y-m-d H:i:s'); 
output: Warning: date_format() expects parameter 1 to be DateTime, boolean given i 

EDIT 2

但是,這會失敗,錯誤「varchar數據類型爲datetime數據類型的轉換導致超出範圍的值」

回答

1

這些可能有助於闡明你要尋找的一些情況。

http://www.ozzu.com/programming-forum/php-mssql-datetime-field-not-pulling-correctly-t106226.html

http://af-design.com/blog/2010/03/13/microsoft-sql-server-driver-for-php-returns-datetime-object/

的strtotime()在你上面的例子返回一個劃時代時間戳。

或檢查CAST和CONVERT(指MSSQL2000但是仍然可以幫助你)
http://msdn.microsoft.com/en-us/library/aa226054%28SQL.80%29.aspx

+0

謝謝。我不明白的是該字段已經是DATETIME字段,因此使用PHP更改其格式不應該很容易嗎? – valoukh

0

如果日期是從MSSQL表中檢索,並要在PHP中使用strtotime(),也不想更改日期格式爲yyyy-mm-dd,那麼你可以使用

CONVERT(VARCHAR(30), DateFromMSSQL, 121) as DateFromMSSQL