0

I want to store php date in sql but it store 1970-01-01 05:00: instead of input datetime

This is html form

<input type="datetime" id="eventstart" name="txtEventStart" class="form-control" value="<?php echo date('m/Y/d h:i:s');?>">

when data is sent using post

$date = $this->input->post('txtEventStart');

I convert string to date format using:

$date2 = date('Y-m-d H:i:s', strtotime($date));

It stores '1970-01-01 05:00:00'

I want to know what is the correct format for storing such type of date.

2 Answers 2

1

Your code is giving you the wrong results because your date is in a format (m/Y/d h:i:s) that is not recognised by strtotime. Instead, use date_create_from_format to convert it and output a date in the correct form for SQL. For example:

$date = '08/2019/19 10:23:41';
echo date('Y-m-d H:i:s', strtotime($date)) . PHP_EOL;
echo date_create_from_format('m/Y/d h:i:s', $date)->format('Y-m-d H:i:s');

Output:

1970-01-01 01:00:00
2019-08-19 10:23:41

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

0

'YYYY-MM-DD hh:mm:ss' is not an acceptable format for PHP date function. Use Y-m-d H:i:s instead. More info here: https://www.w3schools.com/php/func_date_date.asp

Update: For date input field use ISO date format Y-m-d or change input type to 'text'

4 Comments

the one you are suggesting is already tried. it shows '1970-01-01 05:00:00'
You must also use the same format for the 'datetime' input field. Or you can change the input type to 'text'.
dear Aiden there is on need to use the same format, one format can be converted to other
Although I can see that the issue was in your strtotime function, I would like to mention that datetime input format is no longer supported by most browsers. If you would like to set a value for an input type of "date" you MUST use ISO format, m/Y/d format will not be displayed by date input field. This is demonstrated here: onlinegdb.com/BkiOV3t4r

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.