Laravel 5 if statement between Carbon diffForHumans and toFormattedDatesString - laravel

I want to write an if statement to show timestamp in diffForHumans format for timestamps less than less than 5 days old and in toFormattedDatesString for anything older than that.
For example today is 31/10/17, so timestamp for 28/10/2017 should show - 3 days ago and timestamp for 20/10/2017 should show Oct 20, 2017.
What logic should I use to achieve this?

In your Model e.g A.php, create an accessor like this,
public function getCreatedAtAttribute(){
if($this->created_at->diffInDays(Carbon::now()) > 5){
return $this->created_at->toFormattedDateString();
}else{
return $this->created_at->diffForHumans();
}
}
and in your view you can access it as
{!! $a->created_at !!}

Using Carbon you can do that like this.
1
Code
Carbon::createFromFormat('d/m/Y', '28/10/2017')->diffForHumans();
Result
3 days
2
Code
Carbon::createFromFormat('d/m/Y', '28/10/2017')->toFormattedDateString();
Result
Oct 28, 2017

Related

Converting javascript time with php Carbon returns strange time?

I'm setting my time using javascript when creating/updating my cookie.
// get current time
let d = new Date();
let time = d.getTime();
Which variable time becomes this string...
1586186947954
The number above should result 16:29 GMT 6 April 2020
But when I run this number with carbon...
use Carbon\Carbon;
$updated = Carbon::parse($cart['updated']['time']);
This is returned...
Carbon\Carbon Object
(
[date] => 52234-04-07 05:32:34.000000
[timezone_type] => 1
[timezone] => +00:00
)
Which is way off for reason. Minutes and the date are no where near.
I'm trying to output this timestamp in the timezone Asia/Dubai too if I can get Carbon to return the right time anyway.
Any ideas would be great thanks.
The parse method is for parsing more complex strings, so it is misinterpreting the value you're passing.
You should instead construct the object like this:
Carbon::createFromTimestampMs(1586186947954, 'Asia/Dubai')

How to block off a date in Kendo DatePicker

Is there a way to block off a date with the Kendo DatePicker? So if they click open the calendar, and they want to select the 10th of December, I can have that date either disabled or removed ( preferrably disabled ). I don't see any documentation on how to do this.
<div id="datePicker"></div>
$('#datePicker').kendoDatePicker({
// I need it dynamically done, I don't want to hard code the date.
// So if the user clicks it, a request will be handled to send back any dates that are previously taken.
});
For the 10th Dec you can do it like this:
$("#datepicker").kendoDatePicker({
value: new Date(2019,11,5),
disableDates: [new Date(2019,11,10)]
});
disableDates can be an array or a function. You can use dates or weekday names. please check the documentation in my comment to know more. Please notice that 11 is month 12. Why does the month argument range from 0 to 11 in JavaScript's Date constructor?
If you would like to use a function here is how:
disableDates: function (date) {
var dates = $("#datepicker").data("kendoDatePicker").options.dates;
if (your condition) {
return true;
} else {
return false;
}
}

Laravel Eloquent - Get a record every hour

I have a table that stores statistics every 3 minutes with a cron job.
I want to display a chart with this data but I want the chart to have an interval of 1 hour otherwise it looks ugly as hell and is too much resource demanding.
The table has the created_at and updated_at columns.
How can I do this with eloquent?
EDIT: I want to query the records from the last 24 hours but that gives me around 480 records which is too much for a chart. I'd like to have only 24 records instead (one for every hour).
Thanks for your help!
Thanks Tim!
For anyone reading through this later, here is the solution: https://laracasts.com/discuss/channels/laravel/count-rows-grouped-by-hours-of-the-day
Model::where('created_at', '>=', Carbon::now()->subDay())->get()->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('h');
});
This will allow you to get data 1 hours ago base on current time.
//Get all data for the day
$all_data = Model::where('created_at','>=',Carbon::today()->get());
//Recursive to groupBy hours
$i=1;
while ($all_data->last() != null)
{
$hourly_data = Model::where('created_at','>=',Carbon::today()->addHours($i))->get();
$all_data= $all_data->merge($hourly_data);
$i++
}
return $all_data;

Laravel: Querying dynamically Time expressions

In order to list all the articles (films) that are included in our catalog the current month I have written the following query using the Laravel:
$current_month_film = DB::table('films')
->join('categories', 'films.category_id', '=', 'categories.id')
->select('films.*', 'categories.*')
->whereMonth('films.created_at', '=', '12')
->orderBy('films.created_at', 'desc')
->get();
It works perfect. It shows 5 films were added this month. The only problem is that I am hard coding December (month = 12). Next month I will need to update to month = 1. And so on each month; that is a bad solution.
The questions are:
1- How could I get always the current month? Trying
->whereMonth('films.created_at', '=', 'NOW')
give back not error, but the list comes empty. In December there are 5 films added.
2- I am showing a message in front end:
5 films added in Month 12
Is there a way to change the month = 12 into December and show a friendlier message like:
5 films added in December"
3- A better approach would be to show films included within the last 30 days. I did not find a time function for that.
Try to utilise Carbon which comes by default with Laravel.
->whereMonth('films.created_at', '=', Carbon::now()->month)
Since you know $month = 12, you can do something like
$someDate = Carbon::parse("2016" . $month . "01"); //someDate is a Carbon object now
$output = "added in Month " . $someDate->format('F');
Retrieve data 1 month old:
->whereBetween('films.created_at', [Carbon::today()->subMonth(), Carbon::today()])`
Edit: Put in use Carbon; before your class SomeClassName {. You might want to read up about Namespace

Year, Month, and Day parameters describe an un-representable DateTime Exception

I'm adding an object to a list within an ASP.NET MVC 3 application using the following code but one of the properties of the object is giving me difficulties.
ls.Add(new UserRoleModel { UserRoleId = 1, UserName = "Paul", InsertDate = new DateTime(05, 24, 2012),InsertProgram="sqlplus",InsertUser="sp22",Role="Implementation Co-corindator"});
This builds but when I go to the relevant page i get an Exception with the following type:
Exception Details: System.ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime.
I've tried removing the 0 in the month but I get the same exception.
The DateTime constructor you are calling accepts parameters in the order year, month, day.
You are providing them in the order month, day, year -- which ends up trying to assign meaningless values. The documentation is pretty clear on what the allowed values are and what happens if you pass 2012 for the "day" value.
I just ran into this and my issue was I was creating a date in February. I tried to do the following...
new Date(2013, 2, 30)
Since there is not a February 30th, the date failed to create. When I changed to
new Date(2013, 2, 28)
it worked fine.
if the InsertDate meant to be the date / time of creation you can just use the following
DateTime InsertDate = DateTime.Now;
You are using an Invalid datetime, like for month you may be passing 13,14 days more than 31
or something like that which is causing the issue.
i was having the same issue because i was trying to create a DateTime object with date set to 31 of April even though April only has 30 days.
Anyone having the same issue, make sure you are not making this mistake.
Simply you have to change the InsertDate into
InsertDate = new DateTime(Year,Month,Date);
It will solve your problem.
I was facing the same type of issue, where I was using a DateTimePicker in Winform Application. Where user can only pick only month and year and my code and UI was look like
Code
this.dtpMonth.CustomFormat = "MMMM yyyy";
this.dtpMonth.Font = new System.Drawing.Font("Verdana", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.dtpMonth.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
this.dtpMonth.Location = new System.Drawing.Point(88, 24);
this.dtpMonth.Name = "dtpMonth";
this.dtpMonth.ShowUpDown = true;
this.dtpMonth.Size = new System.Drawing.Size(136, 22);
this.dtpMonth.TabIndex = 1;
And I was initializing the by this.dtpMonth=DateTime.Today; and this line cost me and error of current discussion.
Afterward, I have found that my date(DateTime.Today) was 31 July. So, when user want change the month to August it throws exception because August doesn't have date 31. Finally, I change my code into
dtpMonth.Value =new DateTime(DateTime.Today.Year, DateTime.Today.Month,1);
And worked for me.
The same exception I solved as:
DateTimePicker1.Value = DateSerial(Year(Now), Month(Now) + 1, 1)
For those who has this issue, make sure that date, which you try to create exists. For example, I had this problem, because was trying to create 29 feb at not leap year
if you got this error because you're trying to insert 29 days in a year that's not a leap year, then you can check the maximum allowed days first of that year as such:
if(DateTime.DaysInMonth(2024,2) == 29)
dt = new DateTime(2024, 2, 29);

Resources