user3366155
user3366155

Reputation: 452

How to get datetime differance in laravel 4

I am using laravel 4. But I am facing problem with finding the difference between two date: one coming from database table and another one is current datetime. From the date difference I am expecting 1 hour or 1 day. I've tried few solution but can't fix this yet. And also I don't know the better way to solve it. If you guys have any solution, please provide me an example. Please tell me if I need any library. Here is my code:

$lecture_id = Input::get('lecture_id');
        $delegate_id = Input::get('delegate_id');

        // $newDate = new Datetime();

        $lecture = Lecture::find($lecture_id);

        // $lec_date = Date::forge($lecture->start_time);
        // $lec_date = new Datetime($lecture->start_time);

        $lec_date = $lecture->start_time->diffForHumans(Carbon::now());


        if ( $lec_date > 1) {
            LectureDelegate::create(array(
                'lecture_id' => Input::get('lecture_id'),
                'delegate_id'=> Input::get('delegate_id')
            ));
            return Redirect::to('/')->with('message', 'Your are successfully apply to the lecture');
        }

Upvotes: 1

Views: 382

Answers (1)

majidarif
majidarif

Reputation: 20105

Should be:

 $lec_date = Carbon::createFromTimeStamp( strtotime( $lecture->start_time ) )->diffForHumans();

or possibly:

 $lec_date = $lecture->start_time->diffForHumans();

If you add this to your Lecture.php model:

public function getDates()
{
    return array('created_at', 'updated_at', 'deleted_at', 'start_time');
}

From the documentation:

By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon...

You may customize which fields are automatically mutated, and even completely disable this mutation, by overriding the getDates method of the model.

As for diffForHumans the documentation states:

The lone argument for the function is the other Carbon instance to diff against, and of course it defaults to now() if not specified.


update

If the timestamp from the database being passed to diffForHumans is in the future, Carbon automatically makes the return like:

When comparing a value in the future to default now:

  • 1 hour from now
  • 5 months from now

When comparing a value in the past to another value:

  • 1 hour before
  • 5 months before

Upvotes: 1

Related Questions