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.

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 Commented Mar 12, 2016 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. Commented Mar 12, 2016 at 14:13
  • Perhaps use date_parse() first, and only create the DateTime object if it doesn't give you a Boolean false return Commented Mar 12, 2016 at 15:11

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
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.

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.