From MySQL to <input type="datetime-local">

I have a database field (mysql database , of the datetime type) , and it's being filled by PHP. In my html I use an input with the datetime-local type.

From the form , 2014-04-18T18:30 is passed to the mysql database, which stores it as 2014-04-18 18:30:00 .

The thing is : now I want to retrieve said data (to edit the date in my CMS) , and put it as a value into the input field. The issue is that it has to be the old format, not the format mysql converted it to. I can obviously write my own function to take care of it but I'd like to know if there is a default way in php to get it done. Is there an RFC format allowing me to do something like this :

    <?php
$database-date = "2014-04-18 18:30:00"; // this would be retrieved from mysql
$newdate = date(DATE_RFC3339, strtotime($database-date));  // convert it ?
echo $newdate; // I would obviously echo this inside the value of my input

?>

Any help is appreciated.

Upvotes: 4

Views: 16067

Answers (5)

Haritsinh Gohil
Haritsinh Gohil

Reputation: 6272

HTML5 datetime-local input field requires the format to be:

  • A date with format Y-m-d i.e. 2018-09-30.
  • The literal string "T".
  • A time like 23:59.

Example:

"yyyy-MM-ddThh:mm" 2018-12-31T23:59

So as Per above format your input should be as follows:

 <input type="datetime-local" value="<?php echo date('Y-m-d\TH:i', strtotime($database_date)); ?>">

Tip: You can also check your console in your devTools for seeing what is the required format for this date input, if your console is clear then your format is correct otherwise it will display warning as below then you can test the various formats, for you ablove solution is correct:

The specified value "2018-10-16T07:05AM" does not conform to the required format.  The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".      jquery.min.js:3 

Upvotes: 5

didi67
didi67

Reputation: 121

I had the same problem and I solved it by simply putting that in the value field :

value = date("Y-m-d\TH:i:s", strtotime($yourdate))

No need ATOM or W3C

Upvotes: 12

K4timini
K4timini

Reputation: 741

You should use the DateTime class. It's the most recent and standard way to manipulate date.

To create a date from a string there is a way to do that : DateTime:createFromFormat().

More details.

Upvotes: 0

Parag Tyagi
Parag Tyagi

Reputation: 8970

Try DATE_ATOM

 $newdate = date(DATE_ATOM, strtotime($database-date));

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 79024

Check date(). c is ISO 8601 which seems to be the same:

$newdate = date('c', strtotime($databasedate));

Upvotes: 6

Related Questions