1

I have a json with date of users. Dates can be format:

"bdate": "25.10",
"bdate": "8.7.1990"
"bdate": "13.10.1984"
"bdate": "7.3"

How I can parse these dates in carbon globally?

When I use:

Carbon::parse($people->bdate)

I get error:

DateTime::__construct(): Failed to parse time string (25.10) at position 0 (2): Unexpected character

5
  • "bdate": "25.10", what does that format mean, I mean how would you convert that to a normal date? Commented Mar 3, 2019 at 10:20
  • "bdate": "25.10" means: 25 octomber. Commented Mar 3, 2019 at 10:22
  • That's what I figured ... anyway, what year is that? You can't make a date without a year. If I cant figure it out (as a human), It's little surprise a simple piece of code Carbon::parse cant either. Commented Mar 3, 2019 at 10:27
  • @ArtisticPhoenix and then what I can do? I need get birthday date, but service send me dates where year can be, and year can be not. Commented Mar 3, 2019 at 10:30
  • @MafysGrif try \Carbon\Carbon::createFromFormat('d.m', $date)->day; though it needs some work around to match all of your case Commented Mar 3, 2019 at 11:09

2 Answers 2

2

This could be another work around of your problem.

function getBirthDateInCarbon($date){

    $count = substr_count($date,'.');
    if($count==1){
        return \Carbon\Carbon::createFromFormat('d.m', $date);//default year will be current year
    }
    return \Carbon\Carbon::createFromFormat('d.m.Y', $date);
}
Sign up to request clarification or add additional context in comments.

Comments

1

There is probably a more simple solution, tested this and it works

    $date = [null, null, null];
    $data = explode('.', "25.10");

    foreach ($data as $key => $da) {
        $date[$key] = $da;
    }

    $date = Carbon::createFromDate($date[2], $date[1], $date[0]);

Comments

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.