簡體   English   中英

將變量和字符串轉換為日期時間格式

[英]Convert variables and strings to datetime format

我目前有以下變量和格式化的數據:

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

我需要將它們組合到一個類型為“ datetime”的變量“ schedstart”中,以插入我的數據庫,而我完全迷路了。 我嘗試研究這些問題,並找到了使用mktime()或sttodate()的建議,但找不到任何可靠的語法准則。

如何使用PHP合並這些變量?

您可以使用以下使用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

結果:

yourDate
2012-10-01 03:00:00

您可以考慮在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')");

?>

我不知道為什么在PHP中超級容易做到時,為什么要在SQL中這樣做呢?

(通常最好在SQL服務器上施加盡可能小的壓力,因為這通常是瓶頸,再加上,在SQL中使用CONCAT拼湊起來要難看得多)

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

因此,只需要取不同的日期並將它們塞在一起就可以使它們看起來像那樣,然后根據需要在SQL查詢中使用它(用單引號引起來)。

有關更多詳細信息,請參見MySQL文檔

最簡單的方法可能如下所示:

$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' ...");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM