0

I am confused as to why my date is getting converted to unix default before entry into mysql. I am sure the code is correct but cannot see why this is not working. It should convert the date that I post to script.

I would be grateful if someone could check the code and point out my error. Many thanks.

Post: 22/08/2017 05:03:29 Output:1970-01-01 12:00:00

$date = $_POST['datetimepicker'];
$parsedDate = date('Y-m-d h:i:s', strtotime($date));
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user1532468
  • 1,723
  • 8
  • 41
  • 80
  • If the input date comes from a JavaScript date picker you better configure it to format the date in the desired format (`Y-m-d H:i:s`) when it puts the value in the form. – axiac Feb 14 '18 at 11:22

1 Answers1

2

d/m/Y is not one of the date formats recognized by the PHP date parser.
Given the number of digits in the date components, the parser assumes m/d/Y and because 22 is not a valid month number it fails and strtotime() returns 0.

You can use DateTime::createFromFormat() to tell the parser what format do you use:

$date = DateTime::createFromFormat('d/m/Y H:i:s', '22/08/2017 05:03:29');
echo($date->format('Y-m-d H:i:s'));

# 2017-08-22 05:03:29
axiac
  • 68,258
  • 9
  • 99
  • 134
  • This code causes this error: Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href ='datetime.--construct'>datetime.--construct</a>]: Failed to parse time string (22/08/2017 05 :03:29) at position 0 (2): Unexpected character' Thanks – user1532468 Feb 14 '18 at 11:16
  • `22/08/2017 05 :03:29` There is a unwanted space in your time – Scriptman Feb 14 '18 at 11:18
  • It works well as long as the provided input uses the format: https://3v4l.org/KQQZW – axiac Feb 14 '18 at 11:20
  • Not usre if it makes any difference but i am using php 5.3 – user1532468 Feb 14 '18 at 11:28
  • [`DateTime::createFromFormat()`](http://php.net/manual/en/datetime.createfromformat.php) is available since PHP 5.3, it should work without problems. – axiac Feb 14 '18 at 11:40
  • @axiac not sure what you mean by this line: 'It works well as long as the provided input uses the format' thanks – user1532468 Feb 14 '18 at 11:44
  • The date in your first comment is `22/08/2017 05 :03:29`. It contains a space (after `05`) that should not be there. Of course it cannot be parsed. The format specified by the first argument is `d/m/Y H:i:s`. The parser allows one space in the format (between date and time ) match multiple consecutive spaces in the input date but the other pieces must match exactly. – axiac Feb 14 '18 at 11:46
  • Where is that space coming from. It is not in the post? Thanks – user1532468 Feb 14 '18 at 12:00