0

So I currently have a request sending to a function:

$request->date

and date, in this case, is a string "2019-10-15"

The function is expecting \DateTime $scheduled as the argument this date is going to

How can I properly (using Carbon/laravel) convert this date string to dateTime in this request portion where it's being sent?

3 Answers 3

2

In your controller where you need the date, use this:

$date = Carbon::parse($request->date);
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply instantiate a DateTime from that date

new \DateTime($request->date);

You can use DateTime to parse custom formats too

DateTime::createFromFormat('d/m/Y', $dateastring);
//or
$micro = microtime(true);
DateTime::createFromFormat('U.u', $micro);

You can also specify the timezone with the extra parameter

$utcTimezone = new DateTimeZone("UTC");
new \DateTime($request->date, $utcTimezone);
//or 
DateTime::createFromFormat('d/m/Y', $dateastring, $utcTimezone);

5 Comments

OP wants to do with Carbon though.
@vivek_23 not really, the OP wants to do it in laravel, using built-in PHP functions is completely valid here. Carbon can be used but it's not mandatory at all
@Kaddath I do know that but OP said How can I properly (using Carbon/laravel) convert this...
@vivek_23 there is already a good answer using Carbon, i'm just providing a simpler alternative. This answer might give another point of view to the developer about using Framework specific ways or PHP native ways so for me it's a valid answer.
in my case, I have date in french format : dd/mm/aaaa, so I use $datetime = DateTime::createFromFormat('d/m/Y', $dateastring); $datetime->setTime(0,0);
0

As Laravel have no casts support inside request object, I would use passedValidation inside the custom request object:

public function rules()
{
    return [
        'date' => 'required|date',
    ];
}

protected function prepareForValidation(): void
{
    $this->merge([
        'date' => Carbon::parse($this->get('date'))
    ]);
}

public function getDate(): \DateTime
{
    return $this->get('date');
}

Getter is optional, I like it just because it defines a type.

In Laravel we have a Request layer where all this stuff should be handled, controllers might get cluttered if we put casting and parsing into them.

This has not been appropriately tested.

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.