Search code examples
phpmysqltempus-dominus-datetimepicker

Datetimepicker time and date conversion


I've been trying for hours to change the format of my datetimepicker (Tempus DOminus for bootstrap 4) but the format won't change so now I'm trying to find a better way to convert it on the backend when it inserts to my database.

The issue is, the datetimepicker currently puts the user selected date into the input as

10/02/2018 2:15 PM

The problem is, I need to insert it into the database like so:

2018-10-02 02:15:00

Is there a better way that I can just auto convert that to fit the mysql timestamp format I need?

I'm thinking there would have to be a way for me to look at the AM/PM from the datetimepicker and make it either 02:00:00 or 14:00:00 accordingly.

I can convert the date by doing date('Y-m-d') but I don't know how to do the full thing.

Since I'm having issues with the actual picker format, can anyone help me convert this properly?


Solution

  • You can use DateTime::createFromFormat to parse the date format you are getting from your datepicker:

    $datestr = '10/02/2018 2:15 PM';
    $date = DateTime::createFromFormat('m/d/Y h:i A', $datestr);
    echo $date->format('Y-m-d H:i:s');
    

    Output:

    2018-10-02 14:15:00