Is there any way to check that given date is not valid in Carbon, I am using Laravel and default timestamp is 0000-00-00 00:00:00 which is showing as -0001-11-30 06:12:32 and even bad when using ->diffForHumans() its giving me 2044 years ago
I want to do something like this.
return ((string) $model->last_activity == '0000-00-00 00:00:00')
? "Never"
: $model->last_activity->diffForHumans();
is there any simpler way to check that date is not valid, like on any Carbon instance
return $model->last_activity->valid() // return boolean
I will appreciate if you can add this checking in ->diffForHumans() method, so it doesn't return 2044 years ago on invalid dates.
I have checked this solution on SE, but its changes the Carbon date to string
Assuming this is coming from a db, I would expect a nullable value if it really is optional?!? Then you just have a simple null check.
Anyway, you could check the year value $dt->year < 1 or something more like:
return $model->last_activity->lt(Carbon::minValue()) ? "Never" : $model->last_activity->diffForHumans();
Thanks for clarification, keep up the great work
FYI, I needed this too, but minValue() adds a little bit overhead (or not so little if you are calling it multiple times, e.g. in a data grid) probably because it creates a new object each time. Hence I'm doing something like this:
return $model->last_activity->timestamp <= 0
? "Never"
: $model->last_activity->diffForHumans();
Another way would be to cache the value of minValue() somewhere.
+1 For using $model->last_activity->timestamp <= 0 to check for zero-value dates. I wish there was a cleaner way but this has low overhead.
helper function: carbon_date_or_null_if_zero() for handling this in a repeatable way
https://gist.github.com/blur-dave-amphlett/b7076497c273e79a7a552446c169291b
Most helpful comment
FYI, I needed this too, but
minValue()adds a little bit overhead (or not so little if you are calling it multiple times, e.g. in a data grid) probably because it creates a new object each time. Hence I'm doing something like this:Another way would be to cache the value of
minValue()somewhere.