2012-10-01 79 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' ..."); 
相关问题