Laravel Nova: Convert Datetime to readable output - laravel

Is there an option in Laravel Nova to display an readable date-time output and/or limit the output?
For example to : 29. October 2018 / 11. November 2018, 12:10 am
Code:
DateTime::make('Start')
->rules('required')
->sortable(),

As per documentation https://nova.laravel.com/docs/1.0/resources/fields.html#datetime-field
use Laravel\Nova\Fields\DateTime;
DateTime::make('Start')->format('DD MMMM YYYY'),
Must use Moment.js formatting rules https://momentjs.com/docs/#/displaying/format/

This is achieved in Nova 4.0+ with the displayUsing method:
DateTime::make('Updated', 'updated_at')
->displayUsing(fn ($value) => $value ? $value->format('D d/m/Y, g:ia') : '')

use this, hope it will works
Date::make('start')->format('F j, Y'),

We also faced such a problem.
This solution DateTime::make('Start')->format('DD MMMM YYYY'), helps only for index page, but didn't help for Edit page.
I don't know when this bug will be fixed in new Nova releases but we temporary used small hardcoding.
nova/src/Fields/Date.php
instead: return $value->format('Y-m-d');
use this one: return $value->format('m/d/Y');
nova/resources/js/components/Form/DateField.vue
In this vue component also should be changed a date format: dateFormat="m/d/Y".
nova/resources/js/components/Form/DateField.vue
For placeholder method use this one:
return this.field.placeholder || moment().format('MM/DD/YYYY')
Instead this:
return this.field.placeholder || moment().format('YYYY-MM-DD')
Also You should use Mutator in Your App\Model class if you store data in the database in another format. Something like this:
public function setLastUsedAttribute($value){
$date = Carbon::createFromFormat('m/d/Y', $value);
$this->attributes['last_used'] = $date->format('Y-m-d');
}

Related

How to insert date format YY-MM into database?

I have been trying to get the the Year and Month from the user and insert them into the database.
i am using input type month so that the user can send only the Year and the Month.
<input type="month" name="date_from"/>
<input type="month" name="date_to"/>
and this is my model
function setDateFromAttribute($value)
{
$this->attributes['date_from'] = \Carbon\Carbon::createDateFromFormat('Y-m', $value);
}
function setDateToAttribute($value)
{
$this->attributes['date_to'] = \Carbon\Carbon::createDateToFormat('Y-m', $value);
}
protected $fillable = [
'date_from',
'date_to',
];
and data is saved as 0000.00.00
the data type in my database for these two inputs is
timestamp
i do not know what i am doing wrong here. please help
I don't see createDateFromFormat as a valid Carbon method in the documentation https://carbon.nesbot.com/docs/
Likewise, there does not appear to be any createDateToFormat method.
Carbon::createFromFormat() returns a Carbon object, not a string or equivalent MySQL timestamp, so, assuming you change your code to be:
$this->attributes['date_from'] = \Carbon\Carbon::createFromFormat('Y-m', $value)->toDateTimeString();
It should provide the results you are looking for.
References:
Converting a carbon date to mysql timestamp.
#Ted Stresen-Reuter
Sorry for the late reply couldn't find a solution that works within the model. tried your method which i have tried before with minor changes.
thanks a lot for trying to help me.. i found a method to complete this inside the controller which i will not recommend, but this was the best i was able to find which works and i was on a tight schedule.
'date_from' => isset($date_from[$key]) ? date('Y-m-d h:i:s', strtotime($date_from[$key])) : '',
'date_to' => isset($date_to[$key]) ? date('Y-m-d h:i:s', strtotime($date_to[$key])) : '',
the type timestamp accepts at least dates in full formats. as i know how i pass the data from blade to the controller i was able to add a date method and within it a strttotime method to convert my YY-MM into YY-MM-DD and the date that is inserted by default will be 01.

date calculation in laravel model

I want to return values in my model based on dates but not sure how to?
Logic
calculate the date that post has published + 7 days after that and return true or false.
example
Let say I want add new label in posts from the date that post published till 7 days after that, and in the day 8th that new label be removed.
How do I do that?
Update
I ended up with something like this in my model currently
public function isNew($query){
return $query->where('created_at', '<=', Carbon::now()->toDateTimeString());
}
but it returns Undefined variable: isNew in my blade.
please give me your suggestions.
Are labels stored in a separate table from your posts? You could use 'effective dating'. Have indexed 'show_at' and 'hide_at' fields in your labels table. Have entries there get created as soon as the post does. You could use database triggers to do this, or model observers. And when querying for all labels related to a given post, make sure they're between those dates (or those dates are null).
For a more simple solution, you could do a whereRaw('CURRENT_DATE <= DATE_ADD(dateFieldName, INTERVAL 7 DAY)'). If timezones are a factor, you could use the CONVERT_TZ() function, though it's generally good practice to store everything in UTC to avoid those issues.
I would recommend you make use of Carbon:
https://carbon.nesbot.com/docs/#api-difference
That link should help a lot but to point you in the correct direction, you should be able to do a comparison:
I assume you DB date is held in ISO (Y-M-D, eg: 2019-01-07)
$date= Carbon::createFromFormat('Y-m-d', $dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Or if you are using timestamps:
$date= Carbon::createFromTimestamp($dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Solved
thanks for all the helps I solved my issue with code below:
public function getisNewAttribute(){
$now = Carbon::now();
return Carbon::parse($now) <= Carbon::parse($this->created_at)->addDays(7);
}

How to add minutes to to a date in laravel

There are few ways that I can do this using PHP but I could not find a way to do that using laravel specific way.
I have a time that is coming from database in below format: Y:M:s
ex: 05:15:00
This is what I want to do:
add 30 minutes to that date, according to above example result should be: 05:45:00
Below is my current code and I want to add 30min to $endTime:
//get database value according to selected date
$allocatedDateQuery = DB::table('appointments')->where('date', $request->date)->get();
//loop throug every record to get time
foreach ($allocatedDateQuery as $value) {
$time = $value->time;
$endTime = $time;
}
I just got a perfect solution from here.
Use Carbon extention to simply acheive that.
What you have to do is parse your time to Carbon object and then you can use addMinutes() to do that and then you can format() if you want:
foreach ($allocatedDateQuery as $value) {
$time = Carbon::parse($value->time);
$endTime = $time->addMinutes(30);
$allocateValidateMessage .= Carbon::parse($value->time)->format('H:i') . ' - ' . $endTime->format('H:i') . ' ';
}
Usually I use php's date, you can give this a try
Date("Y:M:s", strtotime("30 minutes", strtotime($value->time))
That is converting your time into a string, adding 30minutes to it and converting it to the date format of your desire
Since you said you are grabbing the date from the database I am assuming you are also using Eloquent to query from the database.
You can use Eloquent Mutator Method in your Database Modal Class to mutate the data like this:
public function getAppointmentsAttribute($value) {
return Date("Y:M:s", strtotime("30 minutes", strtotime($value->time)));
}
You can even add another attribute without mutating the original value using Attribute assignments as well. This method caches your query and reduces database calls. Since you do not need to run local loops on the record your code is much cleaner.

Converting String Values into Date using Carbon Laravel

The sql field type is VARCHAR, I am saving date and time from an API. The format that I get is 2018-04-28T22:17:41+05:30. Now I need to convert this using carbon to get a format like 04 April 2018 and timings. I couldn't convert varchar filed value into date format which I needed.
And the expected format should be passed to view, I did that using ( $ticket->dateOfIssue and it's giving this - 018-04-28T22:17:41+05:30 ). But as I said, I need the expected format (which is 04 April 2018, time ).
You should either use Accessor on your model or set the datetime format on your model. The example of the former is:
use Carbon/Carbon; before your class declaration
public function getDateOfIssueAttribute($value) {
return Carbon::parse($value)->format('d M Y , H:m:s');
}
When ever you retrieve this model anywhere you already have it in the format you set in your accessor.
Here is an example to parse the date
Carbon::parse('2018-04-28T22:17:41+05:30')->format('dd MM YYYY');
Moreover, do not forget to import the Carbon namespaces on the top
You try
use use Carbon\Carbon; // on top
$time = Carbon::parse('2018-04-28T22:17:41+05:30')->format('d M Y'); //28 Apr 2018
Good luck
This is the exact format for date and time. First of all include carbon library in your controller
use Carbon\Carbon;
class abc extend Controller
{
public function cancell()
{
$ticket = Booking::all()->where('status', '=', 'CANCELLED');
$dateOfIssue=$ticket->dateOfIssue;
$time = Carbon::parse($dateOfIssue)->format('d M Y , H:m:s');
return view('Admin.Tickets.cancelledTickets')->with('ticket', $ticket);
}
}
If you have multiple records then you can use loop for that
Please try ,
\Carbon\Carbon::parse('2018-04-28T22:17:41+05:30')->format('d- M- Y');
the output is 28- Apr- 2018
using sql
DATE_FORMAT(mydate, '%d-%M-%Y')

Laravel 5.4: How do I get records from just this week?

To get all records of the current day, I did
$dt = Carbon::now();
$dataToday = Data::whereDay('created_at', $dt->day)->get();
To get records from this week, I tried the following but without success.
$dataThisWeek = Data::where('created_at', $dt->weekOfYear);
$dataThisWeek = Data::where('created_at', $dt->weekOfMonth);
$dataThisWeek = Data::whereWeek('created_at', $dt->week);
How do we approach this with Eloquent and Carbon (preferably) or a native MYSQL function?
Try this:
Data::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();
To set the week start/end:
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
You can also try
$dataThisWeek = Data::where(\DB::raw("WEEKOFYEAR(created_at)"), $dt->weekOfYear)->get();
For some reason using Laravel 7.4^ the accepted solution above is not working on my end. No data is shown, to fix it I added a format like this:
$now = Carbon::now();
Data::whereBetween("created_at", [
$now->startOfWeek()->format('Y-m-d'), //This will return date in format like this: 2022-01-10
$now->endOfWeek()->format('Y-m-d')
])->get();
To complete #user320487 answer:
To avoid conflict between different third-party libraries, static setters should not be used. Use $weekEndsAt optional parameter instead when using endOfWeek method.
Data::whereBetween('created_at', [Carbon::now()->startOfWeek(Carbon::SUNDAY), Carbon::now()->endOfWeek(Carbon::SATURDAY)])->get();
You can also use the 'first_day_of_week' locale setting to change the start of week according to current locale selected and implicitly the end of week.

Resources