PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label php-carbon. Show all posts
Showing posts with label php-carbon. Show all posts

Wednesday, November 23, 2022

[FIXED] Why do I get error when try to convert Carbon to DateTime?

 November 23, 2022     laravel, php, php-carbon, phpstan     No comments   

Issue

I am developing a Laravel project. I try to create a DateTime object by using Carbon. This is what I tried:

Carbon::createFromFormat('Y-m-d H:i:s', '2021-10-01T00:01:00')->toDateTime();

But my phpstan complains : Cannot call method toDateTime() on Carbon\Carbon|false.

Why is this error? What is the correct way to convert Carbon to a DateTime object?


Solution

Your format is incorrect, so Carbon cannot create the time. You're missing the T, which needs to be escaped.

Carbon::createFromFormat('Y-m-d\TH:i:s', '2021-10-01T00:01:00')->toDateTime();


Answered By - aynber
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 15, 2022

[FIXED] How to Display product offer for a limited period in Laravel

 November 15, 2022     eloquent, laravel, laravel-6, laravel-7, php-carbon     No comments   

Issue

I need to display as as the product Status is special for a selected date from X date to X date,

This is how my UI Looks like enter image description here

This is the place where a user can create a new sub category and select a special offer dates

enter image description here

This is my Show Function in my Controller

 public function show(Category $category)
{
    // ! Search Filter
    $filter = new SearchFilter();
    $filter->where('parent_id','=',$category->id);

    // ! Date Filter (Today)
     $day = Carbon::now();
     $today = $day->toDateString();
   

    return view('manage.categories.show')->with([
        'pageTitle' => $category->name,
        'allItems' => $this->dataRepo->search([], $filter),
        'isDestroyingEntityAllowed' => $this->isDestroyingEntityAllowed,
        'entity' => $category,
        'today'=>$today,
    ]);
}

This is my blade where it checks the date

@foreach ($allItems as $item)
            <td>
                @if ($item->special_start == $today || $item->special_end == $today)
                    Special
                    @else
                    Regular
                @endif
            </td>

    @endforeach

But this will show Special only if it matches the date with start date and end date, the days between the start date and the end date will be shown as Regular.

How can i fix it ?


Solution

Use Carbon it is not recommended to write logic in view but you can move this to controller

@foreach ($allItems as $item)
<td>
    @php
        $first = \Carbon\Carbon::create($item->special_start);
        $second = \Carbon\Carbon::create($item->special_end);
        $diff = now()->between($first, $second);
    @endphp
    @if ($diff)
    Special
    @else
    Regular
    @endif
</td>
@endforeach

ref link https://carbon.nesbot.com/docs/#api-comparison



Answered By - Kamlesh Paul
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 11, 2022

[FIXED] Carbon.php The separation symbol could not be found Data missing

 March 11, 2022     date, laravel, laravel-5.2, php, php-carbon     No comments   

Issue

First, I retrieve all the records,

//get inventory items
$inv = inventory::all();

and then I loop on the retrieved records and modify the created_at and updated_at data to make it more human readable date.

foreach($inv as $i){
    $i->created_at = date("M d, Y",strtotime($i->created_at));
    $i->updated_at = date("M d, Y",strtotime($i->updated_at));
}

but it returns me this error,

InvalidArgumentException in Carbon.php line 425: Unexpected data found. Unexpected data found. The separation symbol could not be found Data missing

any ideas, help, clues, suggestions, recommendations please?

here's my model

namespace App;

use Illuminate\Database\Eloquent\Model;

class inventory extends Model
{
    protected $table = "inventory";
    protected $primaryKey = "item_id";
    public $incrementing = false;

    public function profile(){
        return $this->belongsTo('App\profile','username');
    }
    public function inventory_images(){
        return $this->hasMany('App\inventory_images','item_id');
    }
}

and in blade, I can just use

{{ date("M d, Y",strtotime($i->created_at)) }}

{{ date("M d, Y",strtotime($i->updated_at)) }}

and it work just fine.


Solution

I think you're going about this the wrong way. The data in your database doesn't need to be more human readable, only the display that a human actually interacts with.

To solve this, we will create a custom accessor method that will apply to all calls for the created_at. You can recreate this for the updated_at.

public function getCreatedAtAttribute($timestamp) {
    return Carbon\Carbon::parse($timestamp)->format('M d, Y');
}

Then when you call $model->created_at your attribute will return in that format.

If for some reason you absolutely need the date stored in that format, then you need to add an attribute to your model telling it that the timestamp columns should be formatted according to a specific type, such as:

protected $dateFormat = 'M d, Y';

Sidenote
The reason that Carbon is involved is that it is applied to all of the columns generated by $table->timestamps(), so the created_at and updated_at columns.
Furthemore, if you add more columns in the model to the protected $dates = [] array, those will also automagically be handled by Carbon.



Answered By - Ohgodwhy
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 9, 2022

[FIXED] Carbon DateTime package

 March 09, 2022     laravel, php, php-carbon     No comments   

Issue

Trying to format a timestamp with Carbon diffForHumans(), passing in the following params, so it reads as:

$new_format = $old_format->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);

When it attempts to format a date ~1 month ago, it leads to an "undefined offset -1" error.

echo Carbon::parse('2022-01-11 15:36:29')->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);
echo Carbon::parse('2022-01-10 16:57:38')->diffForHumans(['parts' => 1, 'options' => Carbon::CEIL]);

The examples above, the top run works, where as the bottom one errors. Is there an explanation, why it breaks with these params, or better yet a solution that would give me the same result? Changing to Carbon::FLOOR or ROUND works fine, but aren't viable for what I need.

Thanks.


Solution

This bug is fixed in version 2.57.0. Thanks for the report.

https://github.com/briannesbitt/Carbon/pull/2547

You can test it using composer update nesbot/carbon



Answered By - KyleK
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 28, 2022

[FIXED] PHP Carbon format to New Date() on Javascript

 February 28, 2022     carbon, html, laravel, php, php-carbon     No comments   

Issue

I want my website changed to full server-side, or with little client-side. What format was used by Carbon to Javascript Date object? Something like this?

Wed Feb 23 2022 12:46:13 GMT+0700 (Western Indonesia Time)

Solution

You can read here for Carbon documentation, and you can format Carbon instance whatever you like

Carbon::now()->format('Y-m-d H:i:s');


Answered By - gguney
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 6, 2022

[FIXED] Pass dynamic value from database to Carbon::now()->subMinutes()

 February 06, 2022     eloquent, laravel, php, php-carbon     No comments   

Issue

I have a minutes integer column in the db,any way to make the below query work without an additional query? Laravel 8 if it matters.

Contest::latest()->where('created_at','>',  Carbon::now()->subMinutes('minutes')->toDateTimeString())->paginate(4)

;

Reponse ErrorException: A non-numeric value encountered in file


Solution

You cannot do this without an additional query. Carbon is a PHP library and won't work within the SQL query. However SQL does provide native functionality for what you need to do:

Contest::latest()
    ->where('created_at','>', DB::raw('NOW()-INTERVAL minutes MINUTE'))->paginate(4)

This should generally work though you may need to replace NOW() with whatever the DBMS provides if not using MySQL.



Answered By - apokryfos
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 29, 2022

[FIXED] Carbon return InvalidArgumentException for a particular format conversion

 January 29, 2022     laravel, laravel-5, php-carbon     No comments   

Issue

I have a date returned from a javascript library in the format 23/10/2019 12:03:46 and while saving in the database i am trying to convert into a carbon object like below:-

 $order->delivery_date =  Carbon::createFromFormat('dd/mm/Y H:i:s',$request->time);

getting error

InvalidArgumentException: Unexpected data found.

also tried these similar links link1 link2 but not able to get out of this problem.


Solution

the format string seems to be wrong. Try it like this:

$order->delivery_date = Carbon::createFromFormat('d/m/Y H:i:s',$request->time);



Answered By - mzolee
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, January 26, 2022

[FIXED] Carbon auto increments time by 11 minutes on parse

 January 26, 2022     laravel, laravel-5, php-carbon, timezone, timezone-offset     No comments   

Issue

I am using Carbon with Laraveal, my local timezone is in IST. I am passing the below ISO string from the UI.

2019-11-22T03:00:00.000Z

When parsed on the server with the below syntax:

\Carbon\Carbon::parse($value)->timezone($this->user->timezone)->format('Y-m-d H:m:s');

The output I am getting is :

2019-11-22 03:11:00

Don't know why I am getting the additional 11 minutes in the time. UI and Server both runs in my local machine. Don't know what's causing the 11 minutes addition.


Solution

->format('Y-m-d H:m:s');

should be

->format('Y-m-d H:i:s');

Notice the m for months and i for minutes.

See PHP docs for formats



Answered By - KFoobar
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 21, 2022

[FIXED] Convert Unix Timestamp to Carbon Object

 January 21, 2022     laravel, php-carbon     No comments   

Issue

I have unix timestamp in table, wants to show to user using Carbon. How can I achieve ?

e.g.

1487663764.99256
To

2017-02-24 23:23:14.654621

Solution

Did you check the carbon docs? I think this is what youre looking for:

Carbon::createFromTimestamp(-1)->toDateTimeString(); 

Checkout http://carbon.nesbot.com/docs/#api-instantiation



Answered By - surgiie
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, January 13, 2022

[FIXED] laravel carbon get day names from a date column from a collection

 January 13, 2022     laravel, laravel-5, php, php-carbon     No comments   

Issue

I have this collection from a database where I have a column called "event_date".

What I want is just to get only the day names from that column that comes in a collection.

I know you can use Carbon to get the name days through, for example, a method called ->format(), however I get an error saying that this method does not exist.

My code so far is as follows:

$collection = MyModel::all();

Inside there is the "event_date" property or column. From that, I want to get the names of the days to put them into an array or collection and finally count those days frequencies.

In order to achieve this I have tried the following:

I tried the ->pluck() method as follows:

$filtered = collect([
            'myDates'=>$collection->pluck('event_date'),
        ]);

And the dd($filtered) looks like as follows:

Collection {#209 ▼
  #items: array:1 [▼
    "myDates" => Collection {#243 ▼
      #items: array:30 [▼
        0 => Carbon {#244 ▼
          +"date": "2017-02-05 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        1 => Carbon {#218 ▼
          +"date": "2017-01-15 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        2 => Carbon {#250 ▼
          +"date": "2016-09-25 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
        3 => Carbon {#249 ▼
          +"date": "2016-05-22 00:00:00.000000"
          +"timezone_type": 3
          +"timezone": "America/Mexico_City"
        }
...

I tried to get the day names as follows:

$Daynames = $filtered->each(function($item,$key){
            return $item->myDates->format('l');
        });

But I got the following error:

Undefined property: Illuminate\Support\Collection::$myDates

Any ideas to get only the daynames into an array or collection? Is there another way to do this?


Solution

You're calling format() on the collection of dates, while you should call it on the Carbon objects. You need another loop that would go through all dates in myDates collection and format them, e.g.:

$Daynames = [];
$filtered->each(function($item,$key) use (&$Daynames) {
  $item->each(function($date) use (&$Daynames) {
    $Daynames[] = $date->format('l');
  });
});


Answered By - jedrzej.kurylo
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to convert any time zone into UTC using Laravel

 January 13, 2022     laravel, php, php-carbon     No comments   

Issue

I want to convert the user's time, eg. 08:45 P.M, to UTC time zone. How can I do that?

if ($request->open_at)
{
  $time = Carbon::parse($request->open_at)->toUTCString();
  dd($time);
  $query->whereTime('open_at', '>=', $time);
}

Solution

Use this PHP approach:

$time = new DateTime("08:45 P.M");
$time ->setTimezone(new DateTimeZone("UTC"));
echo $time ->format("Y-m-d H:i:s e");


Answered By - Faizan Ali
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, January 11, 2022

[FIXED] Laravel Carbon See if date is in the past

 January 11, 2022     laravel, php, php-carbon     No comments   

Issue

I am very confused by this, maybe its something simple I am not seeing. If I want to see if a date is in the past of today I should be able to do something like this?

if( $league->date_start <= Carbon::now() ){
    $join  = false;
    $message = 'Sorry, the league has already started';
}

if I dump out the dates its

$league->date_start = 2017-07-31 00:00:00
Carbon::now() = 2017-11-01 16:29:27

$league->date_start is a protected date so its a carbon instance

But this doesnt work, if I switch it to $league->date_start >= Carbon::now() it works and wont let me join. I know the "league" start date is in the past so shouldnt it be $league->date_start <= Carbon::now()?????


Solution

There's built-in Carbon method isPast so you can use:

$league->date_start->isPast()

to determine if date is in past or not



Answered By - Marcin NabiaƂek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, January 4, 2022

[FIXED] Laravel Carbon, retrieve today's date with weekday?

 January 04, 2022     datetime, laravel, laravel-5, php-carbon     No comments   

Issue

I am using carbon to compare 2 dates with today's date, however I also have another field in a database called weekday which contains values like:

'MO' 'TU' 'WE'

So I don't only want to search and output by dates but also search by a weekday so:

public function show($id)
{   
    $today = Carbon::now();
    $weekday = //whatever carbon or something else has to retrieve today's day
    $event = Event::with('businesses')
       ->where('startdate', '<', $today->format('Y-m-d'))
       ->where('endate', '>', $today->format('Y-m-d'))
       //or where ('weekday') = $weekday?
       ->get();
    return view('events.showEvent', compact('event'));
}

Solution

I'm not sure that Carbon has such formatting, but what you could do is get the wekkday from a map of days and the current week day constant:

$weekMap = [
    0 => 'SU',
    1 => 'MO',
    2 => 'TU',
    3 => 'WE',
    4 => 'TH',
    5 => 'FR',
    6 => 'SA',
];
$dayOfTheWeek = Carbon::now()->dayOfWeek;
$weekday = $weekMap[$dayOfTheWeek];


Answered By - thefallen
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 1, 2022

[FIXED] Integrate carbon library in codeigniter 3

 January 01, 2022     codeigniter, php, php-carbon     No comments   

Issue

i'm having hard time trying to integrate the grate DateTime Library carbon library with in my project in codeigniter 3 I tried this

$this->load->library('carbon');

and it's give me an error

not existing class

i think the problem is namespaces because carbon uses namespace carbon\carbon

Thank you in advance.


Solution

Easy steps:

  1. Direct download: https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Carbon.php

  2. Put Carbon.php at application/libraries

  3. Create Mcarbon.php

    <?php
    
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    require_once dirname(__FILE__) . '/Carbon.php';
    
    use Carbon\Carbon;
    
    class Mcarbon extends Carbon
    {}
    
  4. Put this in your Controller

    $this->load->library ( 'Mcarbon' ); 
    
  5. Call Carbon method in any function. Example:

    <?php
    
    $dt =Mcarbon::createFromDate(2018,2,13,null);
    var_dump($dt->year);
    var_dump($dt->month);
    var_dump($dt->day);
    var_dump($dt->hour);
    


Answered By - Jetwiz
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing