27 Aug

Working with mySQL datetime, Bootstrap DateTimePicker and Laravel 4

I had some trouble formatting my dates for insertion and properly populating them back into my Laravel 4 blade. Here’s my solution:

within the form on edit.blade.php – note the $block->formatDateTime(Form::getValueAttribute(“date_start”)) – this passes the date_start value to the formatDateTime function in Block.php (below)

<div class="form-group">
  <div class="input-group date" id="startDate">
    {{ Form::label('date_start', 'Date/Time Begins') }}
    {{ Form::text("date_start", $block->formatDateTime(Form::getValueAttribute("date_start")), array("placeholder" => "2014-09-09 12:00:00", 'class' => 'form-control')) }}                
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
  </div>
</div>

Function within app/models/Block.php – this formats the datetime from the database to display properly in the form so that the Bootstrap DateTimePicker can handle it

	public function formatDateTime($d) {
		$olddate = strtotime( $d );
		//$newdate = date( 'Y-m-d H:i:s', $olddate );
		$newdate = date( 'd/m/Y H:i A', $olddate );
		return $newdate;
	}

Within the update function in BlockController.php – Formats the date/time string submitted from the input field generated by the Bootstrap DateTimePicker

$startDate = \DateTime::createFromFormat('m/d/Y g:i A', trim(\Input::get('date_start')));
$block->date_start = $startDate;