Laravel format time column in blade - php

In Laravel I know I can use Carbon to format dates into more readable strings. Is there a way to do this for a time column like {{ $event->time->format('h i') }}? All I see in all my searches are related to datetime columns. A lot of the apps I do are for schedules so there is a "Start" time and "End" time. For these I use $table->time('starts'); in my migrations, not a timestamp. The trouble is when I use the field in Blade, I need to format it in 12 hr AM/PM format and I can never find a good way.

try
in the model make sure you have the field in the cast array
protected $casts = [
'created_at' => 'datetime:h i',
];
$event->time->format('h i')->toTimeString()
try below also
public function getformattedAttribute()
{
return \Carbon\Carbon::createFromFormat('h i', $this->attributes['time']);
}
and run it with $event->formatted

Depending on your implementation, you might have some unreliable time generated on conversion, basically because of timezone so I will post with the assumption that you're using something like below:
$table->timeTz('start'); or $table->time('start');
The Difference there is the timezone which can produce incorrect value on conversion as mentioned above.
So, for you to generate format such as 12hr AM/PM which in reality should look like 12:00 PM or 12:00pm or 12:30 PM .....
We can do something like below:
public function dateTest(){
$sampleTimeFromDb = "12:00:00"; //This is the basic sample time you're expected to get from your db ...
$sampleTimeFromDbFormated = Carbon::createFromTimeString($sampleTimeFromDb)->format('g:i a'); // am/pm, you can change a to A to get AM/PM
//Other samples which basically will generate same sample but with time stamp specified
$sampleCurrentTimeLag = Carbon::createFromTimeString("12:00:00","Africa/Lagos");
$sampleCurrentTimeReg = Carbon::createFromTimeString("01:00:00","America/Regina");
$def_format_ = Carbon::createFromTimeString($sampleCurrentTimeLag)->format('g:i A'); //Without timezone AM/PM
$lagosFormat = Carbon::createFromTimeString($sampleCurrentTimeLag, "Africa/Lagos")->format('g:i a');; //with timezone am/pm
$def_format_0 = Carbon::createFromTimeString($sampleCurrentTimeReg)->format('g:i A'); //Without timezone AM/PM
$americaFormat = Carbon::createFromTimeString($sampleCurrentTimeReg, "America/Regina")->format('g:i a');; //with timezone am/pm
$data = [
'_' => $sampleTimeFromDbFormated,
'a' => $def_format_,
'b' => $lagosFormat,
'c' => $def_format_0,
'd' => $americaFormat,
'e' => $americaFormat
];
return View("playground", $data);
}
My view playground.blade.php
<!DOCTYPE html>
<html>
<body>
<p>{{$_}}</p>
<p>{{$a}}</p>
<p>{{$b}}</p>
<p>{{$c}}</p>
<p>{{$d}}</p>
<p>{{$e}}</p>
</body>
</html>
Output:
Hopefully it does help.

Related

Laravel Carbon failed to parse time string error

I import datas from excel with excel maatwebsite laravel to a mysql db, I dunno why but I see that in Excel date column are in text format (and only if i click ENTER inside each cell it became date format),
so the only method to import automatically them that i found is
public function model(array $row)
{
$year_pd = Carbon::parse($row[7])->format("Y");
$day_pd = Carbon::parse($row[7])->format("m");
$month_pd = Carbon::parse($row[7])->format("d");
$hour_pd = Carbon::parse($row[7])->format("H");
$minute_pd = Carbon::parse($row[7])->format("i");
$pickup_date = Carbon::create($year_pd, $month_pd, $day_pd, $hour_pd, $minute_pd);
$year_dd = Carbon::parse($row[8])->format("Y");
$day_dd = Carbon::parse($row[8])->format("m");
$month_dd = Carbon::parse($row[8])->format("d");
$hour_dd = Carbon::parse($row[8])->format("H");
$minute_dd = Carbon::parse($row[8])->format("i");
$drop_date = Carbon::create($year_dd, $month_dd, $day_dd, $hour_dd, $minute_dd);
return new Driveme([
'targa' => $row[14],
'modello' => $row[13],
'driver' => $row[10],
'pickup_date' => $pickup_date,
'drop_date' => $drop_date,
//'pickup_date' => Carbon::createFromFormat($row[7]),
//'drop_date' => Carbon::createFromFormat($row[8]),
]);
but at certain point importation stops and it gives me this error
Could not parse '13/06/2021 19:00':
DateTime::__construct(): Failed to parse time string (13/06/2021 19:00) at position 0 (1): Unexpected character
All dates have the same format, so why it stops casually on a date if they are all similar?
If I use Carbon::createFromFormat($row[7]) it tell me that format date is incorrect
Thx
As I mentioned, 13/06/2021 is being parsed as m/d/Y, due to the PHP strtotime rules. Other dates may appear work because the first digit is between 1-12, but you won't be getting the actual date that you want (You send 01/06/2021 expecting June 1st, but Carbon will return January 6th)). You need to pass the format into the createFromFormat function:
Carbon::createFromFormat('d/m/Y H:i', $row[7]);

How to get the current date and time in YYYY-MM-DD HH: MM? LARAVEL 4

I have a table transaction, inside there is column order_on_sale with default value is 0. Then i also have a table config, inside there is column name with two value that is sale_start_date and sale_finish_date. And there are also time columns with values ​​2018-05-1 18:00 and 2018-05-31 18:00 (YYYY-MM-DD HH: mm).
name and time columns contained in the config table are interconnected,
sale_start_date = 2018-05-1 18:00
sale_finish_date = 2018-05-31 18:00
then when someone orders on sale_start_date and sale_finish_date, the order_on_sale column contained in transaction table will change its value to 1
how do i get the current current time (YYYY-MM-DD HH: mm) to make the change?
$transaksi = new Transaction;
$order_on_sale = 0;
if (Config::get('sale_start_date') && Config::get('sale_finish_date')) {
$order_on_sale = 1;
}
$transaksi->order_on_sale = $order_on_sale;
$transaksi->save();
Below is my code, but I am confused how to get the current date and time if I write such code
thanks for the answers you provide
A bit late answer for questioner but maybe can help someone:
$date = Carbon::now();
$formatedDate = $date->format('Y-m-d H:i:s');
echo($formatedDate);
use the Carbon Library which comes by default with laravel
$date = Carbon::now();// will get you the current date, time
dd($date->format("Y-M-D H:m")); //this will dump the date time in the desired format
Maybe with:
use Carbon\Carbon;
$Now = Carbon::now(new \DateTimeZone('My/TimeZoneifRequired'))->toDateTimeString();
So have you tried using Carbon Class ? as far as i know Laravel 4 supports it.
you can get your current date by doing
$now = Carbon::now()->toDateTimeString();
This will retrieve the current date in the following format YYYY-MM-DD HH:mm:ss (as default)
if you want to get the current date in your mentioned format YYYY-MM-DD HH:mm
by wrapping around Carbon and adding some php functionality you can get so :
$currentTime = Carbon::now()->toTimeString();
$now = Carbon::now()->toDateString() .' '. substr($currentTime, 0, strrpos( $currentTime, ':') ) ;
For further explanation go for the docs : https://carbon.nesbot.com/docs/
simply you can use the below code on the view page.
<p>{{ date('Y-m-d') }}</p>
note: HTML <p> tag is optional.
with hours and minutes
<p>{{ date('Y-m-d H:m') }}</p>

how to enter time-stamps in mysql from an input

I need to insert Timestamp in MySQL from input in Laravel application
data coming from my input is in this format 12/27/2017 MM/DD/YYYY how can I convert it into this format Y-m-d H:i:s
any alternatives are highly appreciated like pass data from the input which input we use so, I can get data in timestamp format.
and at the end, I need to sort data order by date
If you want to do it in Laravel way you can use mutator and Carbon. This is an example of model:
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model
class Post extends Model {
protected $dates = ['date'];
public function setDateAttribute($value)
{
$this->attributes['date'] = Carbon::createFromFormat('d/m/Y', $value);
}
}
Now when you update or create post date attribute will be automatically converted. So you can save it like this:
$post = new Post();
$post->date = '16/12/2017';
$post->save();
You can use DateTime:
$inputDate = \DateTime::createFromFormat('m/d/Y', '12/27/2017');
$formatedDate = $inputDate->format('Y-m-d H:i:s');
As for me I done date conversion in this way, for example to making invoices. I hope this can be done by PHP.
$input_date = "12/15/2017"; // input in MM/DD/YYYY
$output_date = date('Y-m-d H:i:s',strtotime($input_date)); //set output to 2017-12-15 00:00:00
echo $output_date; //produce output
It generates the following result
2017-12-15 00:00:00
I hope this will work. If you want only date, you can omit H:i:s based on your purpose. Thank you.
$date=date_create("12/27/2017");
$rawDate = date_format($date,"Y/m/d");// Produced - 2017/12/27
echo str_replace('/','-',$rawDate ); // Output - 2017-12-27
to add H:i:s, if there is no time just add 00:00:00 at the end of date begins with space.
If you're dealing with created_at or updated_at which Laravel create for every table, you must add 00:00:00 to end of date to get all data begins with that respective date
This solution worked for me if we want the format of date from input is different from the format the timestamp accepts
Laravel way of doing is
protected $fillable = ['organization_name', 'job_apply_link', 'job_description', 'city_id', 'province_id', 'sector_id', 'image_file', 'test_id', 'newspaper_id', 'catagory_id', 'slug', 'meta_keywords', 'meta_description', 'job_title', 'created_at'];
public function setCreatedAtAttribute($value)
{
$inputDate = \DateTime::createFromFormat('m/d/Y', $value);
$formatedDate = $inputDate->format('Y-m-d H:i:s');
$this->attributes['created_at'] = $formatedDate;
}

Check if a date is equal to other date using Laravel 5.3

I am trying to check if one date is equal than the other date, but I can't get the match because the date format coming from the form turns into a different order once it gets through the "parse" code.
I need to format this date to find the match, here is a sample code to show how I am trying:
...
// $ago will give me this date: 2016-12-09 00:00:00
$ago = Carbon\Carbon::today()->addDays(2); // Todays date + 2 days
//$request->datex has the date coming from a form with this format, '12-06-2016'.
// Once a parse $request->datex here, the date gets out of order:
$my_date = Carbon\Carbon::parse($request->datex);
// it shows the date like this, 2016-09-12 00:00:00 , I need it to be on this format: 2016-12-09 00:00:00
// then I could do this:
if ( $ago$ == $my_date ) {
dd($my_date.' is equal to: '.$ago );
}else{
dd(' Not equal!');
}
...
Thanks for looking!
Change this line
$my_date = Carbon\Carbon::parse($request->datex);
with this:
$my_date = Carbon::createFromFormat('m-d-Y', $request->datex)
I've assumed that your format '12-06-2016' means DAY-MONTH-YEAR
UPDATE
Tested my solution on my machine and it works, date is recognized properly:
When
$request->datex = '12-06-2016'
then
$my_date = \Carbon\Carbon::createFromFormat('m-d-Y', $datex);
gives me date like that: public 'date' => string '2016-12-06 18:52:09.000000' (length=26)
Date has been parsed properly. The thing that I've assumed just now. These dates won't be same cause of hours, minutes, seconds and milliseconds. To fix that just we have to compare dates that way:
if ( $ago->format('Y-m-d') == $my_date->format('Y-m-d') )
//do something awesome with our equal dates
PHP expects DD-MM-YYYY or MM/DD/YYYY formats.
If you always have a MM-DD-YYYY format, you could do this before parsing:
$request->datex = str_replace('-', '/', $request->datex);

Converting a carbon date to mysql timestamp.

I have a timestamp variable column in a mysql database. Trying to convert a carbon timestamp to something that I can input there, but Carbon::now() only returns a Carbon object and when I try to use the timestamp string of the Carbon object, it does not register in mysql.
public function store(CreateArticleRequest $request){
$input = $request->all();
var_dump($input); // JUST SO YOU CAN SEE
$input['published_at'] = Carbon::now();
var_dump($input); // JUST SO YOU CAN SEE
Article::create($input);
}
My first var dump is like so:
array (size=4)
'_token' => string 'Wy67a4hWxrnfiGz61wmXfYCSjAdldv26wOJiLWNc' (length=40)
'title' => string 'ASDFasdf' (length=8)
'body' => string 'asdfasdf' (length=8)
'published_at' => string '2015-08-26' (length=10)
My second var dump is like so.
The mysql column relating to "published_at" is a timestamp variable. How an I suppose to convert this from a Carbon Object?
Thanks in advance.
The short answer is that toDateTimeString() is what you're looking for:
$input['published_at'] = Carbon::now()->toDateTimeString();
See http://carbon.nesbot.com/docs/ for more options, including toDateString() if you just want the date part and not the time.
But an even better way to handle it would be to let Laravel handle casting the date value to/from a Carbon object for you. See https://laravel.com/docs/5.4/eloquent-mutators#date-mutators.
The problem is in your date string, for example, you have this:
public function setCrbDateAttribute($value)
{
$this->attributes['crb_date'] = \Carbon\Carbon::createFromFormat('d-m-Y h:i', $value);
}
Now, if there is a date like 10-12-2014 then this error will occur because the hour and minute is missing. So you make sure that the date contains all the pars and also make sure that the date string contains - as a separator not /.
In other words, check the $value before you use Carbon and make sure your date string contains exactly the same formatted string you've used in the method.
This also happens in an accessor method, so check the date value first before you use it in Carbon::createFromFormat().
If you are getting the date from user input then validate the date before using it using date or date_format:format rule, check the validation here.
Answer ref:
Laravel/Carbon Timestamp 0000-00-00 00:00:00 or Unexpected data found. Unexpected data found. Data missing
You can also set Mutator on your model.
public function setPublishedAt($value)
{
$this->attributes['published_at'] = strtotime($value);
}
to convert to timestamp
$model -> setPublishedAt('2015-08-26'); // 1440572400
or you can just convert the date to timestamp using strtotime
strtotime — Parse about any English textual datetime description into a Unix timestamp
Hope this help.

Categories