2012-10-01 38 views
0

我現在有下列變量和格式化的數據:轉換變量和字符串日期時間格式

  • Scheduling_StartDate_Month = 10
  • Scheduling_StartDate_Day = 1
  • Scheduling_StartDate_Year = 2012
  • Scheduling_StartTime = 3:00 PM

我需要將它們組合成一個'datetime'類型的變量'schedstart't o插入我的數據庫,我完全失去了。我試圖研究這些問題,並找到了使用mktime()或sttodate()的建議,但我找不到任何可靠的語法指導。

如何將這些變量與PHP結合使用?

回答

1

你可以考慮以適當形式串聯在PHP :

<?php 

$dateString = $Scheduling_StartDate_Month."/".$Scheduling_StartDate_Day."/".$Scheduling_StartDate_Year." ".$Scheduling_StartTime; 
$result = mysql_query("SELECT STR_TO_DATE('".$dateString."', '%m/%d/%Y %h:%i %p')"); 

?> 
+0

有什麼辦法可以做到這一點只是在PHP? – Michelle

3

您可以使用它使用STR_TO_DATE()CONCAT()功能如下:

select 
    str_to_date(
    concat(Scheduling_StartDate_Year,'-', 
      Scheduling_StartDate_Month, '-', 
      Scheduling_StartDate_Day, ' ', 
      Scheduling_StartTime), '%Y-%m-%d %h:%i') as yourDate 
from yourtable 

SQL Fiddle With Demo

結果:

yourDate 
2012-10-01 03:00:00 
0

我不知道爲什麼地球上你想用SQL來完成這項工作,因爲它在PHP中非常容易。

(通常最好把儘可能少的應變儘可能的SQL服務器上因爲這是通常的瓶頸,再加上,它更醜陋拼湊在SQL中使用CONCAT

MySQL的日期,基本上只是字符串以特定方式格式化。例如2008-12-31 23:59:59

所以,只要把你的不同日期片段放在一起,讓它們看起來像那樣,然後在你的SQL查詢中使用它(把它放在單引號中)。

查看MySQL docs瞭解更多詳情。

最簡單的方法可能是這樣的:

$mysql_formatted_date = date('Y-m-d H:i:s', strtotime("Scheduling_StartDate_Year-$Scheduling_StartDate_Month-$Scheduling_StartDate_Day $Scheduling_StartTime")); 

即讓strtotime解析出你的約會和處理AM/PM轉換爲24小時的時間,然後用date迫使它進入正確的格式。

mysql_query("SELECT '$mysql_formatted_date' ..."); 
相關問題