Laravel: Get time between two timestamps in diffForHumans format (Carbon) - php

I am trying to get the time between two dates in diffForHumans format, can anyone help me out to why its throwing this error?
Code:
{{ Carbon\Carbon::createFromTimestamp($clientLogin->exit_timestamp)->diffForHumans($clientLogin->enter_timestamp) }}
Error:
Type error: Argument 1 passed to Illuminate\Cookie\Middleware\EncryptCookies::encrypt() must be an instance of Symfony\Component\HttpFoundation\Response, instance of Illuminate\View\View given

Suggestion: Define your datetime fields as dates so Laravel can treat then already as a carbon instance, so you can do something like this:
$clientLogin->exit_timestamp->subDays($clientLogin->enter_timestamp)->diffForHumans();

Related

Trying to convert a date in Twig

I'm trying to convert this:
{{ "26/03/2013"|date("d/m/Y") }}
in Twig but its is throwing the error
Uncaught Exception: DateTime::__construct(): Failed to parse time
string (26/03/2013) at position 0 (2): Unexpected character in
/home/vagrant/Code/Phantom
Website/vendor/twig/twig/lib/Twig/Template.php on line 218.
If I pass this:
{{ "03/26/2013"|date("m/d/Y") }}
It works, so I imagine I need to change something related to Twigs date formatting
The date filter is about formatting DateTime Object, so if you pass a string this will be passed to the constructor of the DateTime object then to the format method, so in your case, you need to format the string that looks good for a DateTime constructor as example
{{ "2013-3-26"|date("d/m/Y") }}
From the doc:
The format specifier is the same as supported by date, except when the
filtered data is of type DateInterval, when the format must conform to
DateInterval::format instead.
And also about string format:
The date filter accepts strings (it must be in a format supported by
the strtotime function), DateTime instances, or DateInterval
instances. For instance, to display the current date, filter the word
"now":
Try this in this twigfiddle
If you use /'s as delimiter the expected format is m/d/Y,
To pass the date as day, month, year you need to use a - as delimiter
{{ "26-03-2017" | date('d/m/Y') }}
fiddle

Laravel5 Eloquent default date mutator fails with JSON date input

I've a model with date mutators, such as created_at. Let's say a generic timestamp property.
When passing data from the client in JSON format, i'll get
{
timestamp: "2016-06-07T22:00:00.000Z"
}
That property will be used to set some model like so:
$model = new Foo();
$model->timestamp = Input::get('timestamp');
Since this will trigger the date mutator, php Carbon gets called and fails with
InvalidArgumentException in Carbon.php line 425
Unexpected data found.
Trailing data
Now, that's not an issue with Carbon itself, that is able to handle JSON formats. If you'll try
new Carbon('2016-06-07T22:00:00.000Z');
you'd infact get the expected result.
From what i see, the problem origins from a weird Eloquent behaviour. See this trace from the above mentioned InvalidArgumentException in Carbon.php line 425:
in Carbon.php line 425
at Carbon::createFromFormat('Y-m-d H:i:s', '2016-06-07T22:00:00.000Z') in Model.php line 2915
at Model->asDateTime('2016-06-07T22:00:00.000Z') in Model.php line 2871
at Model->fromDateTime('2016-06-07T22:00:00.000Z') in Model.php line 2826
at Model->setAttribute('timestamp', '2016-06-07T22:00:00.000Z') in Model.php line 3351
Eloquent is trying to createFromFormat passing a bad format which doesnt mirror the actual JSON format, that is causing the Carbon exception.
On the other hand, a simple call like the above mentioned new Carbon($jsonDate) would work fine in this case.
How should i approach to solve this?
Isn't this supposed to be an Eloquent bug?
== EDIT ==
I didn't code any mutator myself. I'm using default date mutators like so:
public function getDates() {
return ['timestamp'];
}
Eloquent analyses the date you give it, when the attribute is set in the getDates function.
In it's analyses it has four steps: (see Modal.php asDateTime method for clarification, the code is pretty well commented: https://github.com/illuminate/database/blob/master/Eloquent/Model.php#L2898)
If it is already a Carbon instance, use that
If it is an instance implementing DateTimeInterface, use that
If it is numeric, parse as a Unix timestamp
If it is a simple year month day format (tried by regex) use that
If none of the above, create a Carbon instance with the format you specify as default
In you case, 1-4 don't match, so it tries 5.
You have no custom dateFormat specified on the model, so it uses the default date format applicable to the type of database connection you are using. You can override this by adding a $dateFormat variable to the model:
protected $dateFormat = 'U';
But your normal timestamps are probably in the correct format already. So this solution would not work for you.
In your case I would just do:
$model->timestamp = Carbon::parse(Input::get('timestamp'));
Or use Carbon::createFromFormat() with the appropriate format.
I don't exactly know why they don't just parse it with Carbon directly. I guess it is more error prone and less controllable. With different international formats you might get an unexpected outcome (month and day switched etc). It might also be slower than their current approach.

DateTime format expects parameter 1 to be string, Object given - Symfony2

I'm having some troubles using the format function in Symfony2 when trying to insert a date interval into a table, for the purpose of setting due dates for created invoices.
Here is what I have:
$today = new \DateTime();
$interval = $today->add(new \DateInterval('P1M'));
$invoice->setDueDate($interval->format('Y-m-d H:i:s'));
However, when I hover over the format parameter in PHPStorm, it tells me that it's expecting a DateTime object not a string, and I get the following error in my profiler:
Error: Call to a member function format() on string
So, I changed the line to this:
$invoice->setDueDate($interval->format(new \DateTime()));
But when I run that, my profiler gives this error:
Warning: DateTime::format() expects parameter 1 to be string, object given
It almost seems like a catch 22 situation! I am really baffled, do I use a string or a DateTime object, because either one fails yet warns me I need to use one or the other..
Any ideas?
I’d guess that $invoice->setDueDate() is the one expecting a DateTime instance. So the line should be $invoice->setDueDate($interval);

Date gives as result 2024 instead of 1924 Twig

In the database, I have following date: 1924-01-17, as a date-type, but when I render it as {{ person.BirthDate | date("d/m/Y") }}, it gives as a result 17/01/2024.
How can I solve the Year-problem?
Twig documentation for date says:
The date filter accepts strings (it must be in a format supported by
the strtotime function), DateTime instances, or DateInterval
instances.
DateTime instance should do the trick, and based on comments it fixed this.

PHP using Laravel 4 and Carbon will not print out a DateTime field from my Database

I am building a PHP application with Laravel 4.
I am getting errors when I try to print out a DateTime record from the Database though.
{{ $user->created_at }}
Gives me this error
InvalidArgumentException
Trailing data
open: E:\Server\htdocs\projects\timeclock\www\vendor\nesbot\carbon\src\Carbon\Carbon.php
Very frustrating!
An example value from that Database field is: 2013-08-31 20:50:25.
You are missing the milisecond data on the time stamp, you need to use:
Carbon::createFromFormat('Y-m-d H:i:s.u', $value)->format('d/m/Y H:i:s');
You have to format it:
{{ $user->created_at->format('h:i:s') }}
The PHP docs has a list of all the codes available to use as a format.
I have the same issue.
And I found that this is caused by my timestamp data in database.
2013-12-13 22:40:50.561709 <- this one will cause the issue.
2013-12-13 22:40:50 <- this one will not.
Timestamp value with millisecond causes this issue.
Column which is converted to Carbon object can not have millisecond timestamp.(default: created_at, updated_at).
http://readouble.com/laravel/4/2/0/en/eloquent.html#date-mutators
If Carbon Object is not necessary, you can disallow auto-converting.
class SomeModel extends Eloquent {
public function getDates()
{
return array();
}
}
But it also make Carbon methods(ex:->format()) unavailable. You have to format timestamps in other way.

Categories