2017-05-22 31 views
0

我有什麼似乎是一個相對簡單的問題,導致比我想象的更多的問題。正如您可能知道的那樣,HTML5不再支持表單字段的「datetime」輸入,並且只支持「datetime-local」。當我嘗試通過我的網站上的表單將「datetime-local」插入到我的數據庫中時,由於「datetime-local」中包含額外字符,我顯然遇到錯誤。我正在嘗試做什麼,以及爲什麼我需要一個日期時間字段而不是他們各自字段中的日期和/或時間,是因爲我想使用碳來以不同的格式顯示我的日期時間。我怎樣才能通過HTML表單插入日期時間到MySQL表,而無需手動將值插入到我的數據庫?如何使用HTML表單將datetime正確插入MYSQL數據庫?

編輯: 這是所有我試圖實現這一目標的相關代碼。我使用Laravel來構建這個應用程序

遊戲/創建表單:

<select name="season_id"> 

     @foreach ($seasons as $season) 

     <option name="season_id" value="{{ $season->id }}">{{ $season->season }} {{ $season->year }}</option> 

     @endforeach 

</select> 

<label for="inputDateTime" class="sr-only">DateTime</label> 
    <input type="datetime-local" name="gdatetime" id="inputDateTime" class="form-control" placeholder="DateTime" required autofocus> 

<label for="inputOpponent" class="sr-only">Opponent</label> 
    <input type="text" name="opponent" id="inputOpponent" class="form-control" placeholder="Opponent" required autofocus> 

<label for="inputLocation" class="sr-only">Location</label> 
    <input type="text" name="location" id="inputLocation" class="form-control" placeholder="Location" required autofocus> 

<label for="inputField" class="sr-only">Field</label> 
    <input type="text" name="field" id="inputField" class="form-control" placeholder="Field" required autofocus> 

遊戲控制器:

$game = Game::create(request(['gdatetime', 'opponent', 'location', 'field', 'season_id'])); 

而且,在我的Game模型,我已經定義了這一點:

protected $dates = ['gdatetime']; 
+0

這是用戶輸入的時間/日期還是記錄保存? – GrumpyCrouton

+0

這是一個用戶輸入日期時間@GrumpyCrouton – hoolakoola

回答

1

您可以隨時分析你輸入的日期時間到碳實例並將它們存儲在數據庫中。解析將關注在存儲之前格式化輸入的頭痛。您可以隨時以任何格式顯示它們。

$date = \Carbon\Carbon::parse($request->input('datetime')); 

編輯:根據您的意見和更新,做到這一點。

$data = request(['opponent', 'location', 'field', 'season_id']); 

$data['gdatetime'] = \Carbon\Carbon::parse(request('gdatetime')); 

$game = Game::create($data); 
+0

當我嘗試這個 – hoolakoola

+0

@hoolakoola時,我得到一個未定義變量'request'的錯誤,這是一個關於如何使用表單輸入的例子。您可以用日期時間值替換'$ request-> input('datetime')'或者如何獲取表單輸入。 – Sandeesh

+0

好的,當我將它改爲'$ date = \ Carbon \ Carbon :: parse('gdatetime');'我得到另一個錯誤,'DateTime :: __ construct():無法解析時間字符串(gdatetime) g):在數據庫中找不到時區# – hoolakoola

0

使用PHP將其轉換。

date('date format here', strtotime($user_input); 

date()

strtotime()

而且始終確保驗證用戶輸入的服務器端,否則可能strtotime()返回false造成date()回到1969年

0

或者你可以在你的模型文件中定義的:

protected $dates = ['your_date_field]; 

,當你從數據庫中獲取它,它會是一個碳實例。

相關問題