2

I keep getting the following error :

DateTime::__construct(): Failed to parse time string (46-61-9481) at position 0 (4): Unexpected character

which relates to this piece of script within an API

 $dob = new DateTime(str_replace('/','-',Input::post('date_of_birth')));
  $customer->date_of_birth = $dob->getTimestamp();

I have quite limited knowledge when it comes to code but, I'm wondering if anyone would be kind enough to let me know what to change to avoid these errors.

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
Jamie
  • 21
  • 1
  • 3
  • 2
    Surely it doesn't require much coding knowledge to recognise that `46-61-9481` is unlikely to be recognised as a valid date in most calendar systems – Mark Baker Mar 12 '16 at 14:06
  • The errors happen when a customer puts the wrong date in to the form. Regardless of what they put in, i still want the form to submit the details - we can amend the date when we speak to the customer. – Jamie Mar 12 '16 at 14:13
  • Perhaps use [date_parse()](http://php.net/manual/en/function.date-parse.php) first, and only create the DateTime object if it doesn't give you a Boolean false return – Mark Baker Mar 12 '16 at 15:11

2 Answers2

3

The problem here is the use of DateTime(). PHP DateTime() expects a valid date and otherwise it will throw an exception. If you still want to accept invalid date input, better to put this in a try catch block. If the date is a valid one, it will work well and otherwise it will come to catch block. In the catch block, you can set a default date such as 00/00/0000 and save to DB.

try {
    $date = new DateTime('01-01-2016');
    $date = $date->format('m/d/Y');
} catch (\Exception $e) {
    $date = '00/00/0000';
}

echo $date;
Tibin Paul
  • 806
  • 9
  • 23
0

46 is not a valid month, nor a valid day of month. A valid month or day of month never starts with a 4.

The date 46-61-9481 is invalid, hence the error.

The solution is to validate the input date prior to passing it to DateTime constructor.

Community
  • 1
  • 1
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
  • Thanks Alex, the fact they put in a wrong date isn't an issue, we can amend the date when we speak to the customer, i still want the form to submit regardless of whether the date is correct or not. Is there anything i can do to ensure the form is submitted regardless of what date the customer puts. – Jamie Mar 12 '16 at 14:14
  • Well, you can, for example, check that the date-string is valid and if it is not, you can: Show an error message _or_ set `$customer->date_of_birth` to `null`. – Alex Shesterov Mar 12 '16 at 19:56