Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Carbon date with string

Tags:

laravel

I got a date:

19/02/2018 00:00:00

I want paginate in decrescent order, so I got to create a carbon date...

I got this to show the 10 first days:

$today = Carbon::today();
$lastDays = array();

for ($i = 1; $i < 10; $i++) {
    $day = $today->subDays(1)->format('d/m/Y');
    $lastDays[] = $day;
}

But I want to show more, and this is to show more:

    $today = Carbon::createFromFormat('d-m-Y H:i:s',  '19/02/2019 00:00:00'); 

$lastDays = array();

for ($i = 1; $i < 10; $i++) {
    $day = $today->subDays(1)->format('d/m/Y');
    $lastDays[] = $day;
}

Don't works... returns:

"Unexpected data found. ↵Unexpected data found." On first line.

like image 677
Valter Sousa Cardoso Avatar asked Feb 20 '18 10:02

Valter Sousa Cardoso


People also ask

How do you convert a string to a Carbon date?

$date = Carbon\Carbon::parse($rawDate); well thats it. You'll now have a Carbon instance & you can format the date as you like using Carbon helper functions.

How do you set the date on Carbon?

Carbon also allows us to generate dates and times based on a set of parameters. For example, to create a new Carbon instance for a specific date use the Carbon::createFromDate() method, passing in the year, month, day, and timezone, as in the following example.

What is Carbon :: now ()?

Carbon::now returns the current date and time and Carbon:today returns the current date. $ php today.php 2022-07-13 15:53:45 2022-07-13 00:00:00. This is a sample output. Carbon::yesterday creates a Carbon instance for yesterday and Carbon::tomorrow for tomorrow.

What is Nesbot Carbon?

An API extension for DateTime that supports 281 different languages.


2 Answers

You need to change your code like this. You have provided the wrong format to createFromFormat function.

$today = Carbon::createFromFormat('d/m/Y H:i:s',  '19/02/2019 00:00:00'); 

$day = $today->subDays(1)->format('d/m/Y');
like image 169
Suraj Avatar answered Sep 22 '22 23:09

Suraj


With Carbon there is an method called parse that takes a string and outputs your date. If the given string isn't valid it takes the current date as a default date.

Carbon::parse('your date')->format('your format');

So in your case you should do this:

$today = Carbon::parse('19/02/2019 00:00:00'); 
$lastDays = array();

for ($i = 1; $i < 10; $i++) {
   $day = $today->subDays(1)->format('d/m/Y');
   $lastDays[] = $day;
}

I hope it helps.

like image 42
diakosavvasn Avatar answered Sep 22 '22 23:09

diakosavvasn