简体   繁体   中英

Format date format php

I'm using a DateTimePicker.

<div class="input-group date form_datetime">
    <input type="text" size="16" readonly class="form-control">
    <span class="input-group-btn">
        <button class="btn btn-success date-set" type="button"><i class="fa fa-calendar</i></button>
    </span>
</div>

It returns a date/time with this format: 16 October 2014 - 14:50 .

But my problem is how do I format this format and store it into my database.

date_parse comes to the rescue:

php> $a = '16 October 2014 - 14:50'
php> var_dump(date_parse($a))
/* ⇒
array(12) {
  'year' =>
  int(2014)
  'month' =>
  int(10)
  'day' =>
  int(16)
  'hour' =>
  int(14)
  'minute' =>
  int(50)
  'second' =>
  int(0)
  'fraction' =>
  double(0)
  'warning_count' =>
  int(0)
  'warnings' =>
  array(0) {
  }
  'error_count' =>
  int(1)
  'errors' =>
  array(1) {
    [16] =>
    string(20) "Unexpected character"
  }
  'is_localtime' =>
  bool(false)
}
*/

Hope it helps.

If you still don't have the name="" attribute on the text, then kindly do so:

<input name="date" type="text" size="16" readonly class="form-control" />

Then in PHP:

$date = $_POST['date']; // form input

$datetime_object = DateTime::createFromFormat('d F Y - H:i', $date); // feed the proper format
$insert_date = $datetime_object->format('Y-m-d H:i:s'); // datetime format

// the rest of insertion is up to you. Either use MYSQLI or PDO

Mysql has a date format of YYYY-MM-DD, so very simple with date function. HERE we go...

<?php
 $dateTime='6 October 2014 - 14:50';
 list($date,$time)=explode(' - ',$dateTime);
 echo date('Y-m-d H:i:s', strtotime($date.' '.$time));
 // code here
 ?>

Remember in your db field to store that value, its data type is DATETIME

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM