How to extract the time from "created_at" with Carbon - php

I am struggling with the Carbon functionalities within Laravel framework still. I created these functions used in my model to extract the date of the "created_at" field in my tables:
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y');
}
This works fine for the date, but how would I need to write a function in this model, that will extract only the time within the created_at field?

I feel like you're limiting yourself a lot be overriding the default behaviour for dates.
If you remove your accessor (getCreatedAtAttribute) you'll be able to call format from the property itself i.e.
$model->created_at->format('d.m.Y')
or
$model->created_at->format('H:i:s');//e.g. 15:30:00
Carbon is just a wrapper for DateTime. For a list of format characters you can look here: http://php.net/manual/en/function.date.php
e.g. todays date as 6th February 2016 would be jS F Y

try to use
public function getCreatedAtAttribute($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('H:i:s');
}
output will be time

If you want to insert date into database manually you can do this.
"created_at" => now(),
"updated_at" => now()
debugging
dd(now());
// output
// 2022-03-16 10:24:07

$model->created_at
This will use some Eloquent magic and return the creation date as a Carbon object.

You can create an helper for it. This will allows you to call the getTimeFromCreatedAt() function anywhere in your laravel code.
//extracts time from created_at column
function getTimeFromCreatedAt($date) {
return Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('H:i:s');
}

Related

Getting only time from Carbon object

Im reading an excel file a column with values like "1:45:00. But when print_r($value["time"]) this value from my array I got a Carbon object like this:
Carbon\Carbon Object
(
[date] => 2018-10-30 01:45:00.000000
[timezone_type] => 3
[timezone] => America/US
)
Then, when I insert to a bulk array my value with:
"time"=>$value["time"]
In the database I got: 2018-10-30 01:45:00
How can I insert only 01:45:00 and not the entire timestamp?
EDIT: I thought that $value["time"]->date->format("H:i:s") would works but I got the error "Trying to get property 'date' of non-object"
EDIT 2: This is how I read the data:
The excel is like:
date time
---------- -------
30-10-2018 01:45:00
The code where I read the excel:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
die();
}
The output:
Call to a member function format() on null
What you need is the formatting here:
$dt = Carbon::now();
$dt->toTimeString(); //14:15:16
Carbon\Carbon is an extension to php's DateTime, so you can read at php.net to learn more.
Although America/US is not a valid timezone, so there's something going on with that.
Anyway,
In the database I got: 2018-10-30 01:45:00
If your data type is a TIMESTAMP or a DATETIME, mysql will always have a date component for data in that column.
First, let's get the time out of the $value array to make the rest of the discussion easier to understand and debug:
$time = $value["time"];
From here on out, pay no attention to the internal fields revealed by var_dump. They may or may not actually exist like that in the object. Use the mostly-well-documented interface methods documented in the link above or in the Carbon docs. The fields given by var_dump will just confuse you otherwise.
If you just want the time of day represented as a string, you use the DateTime::format() method:
$timestr = $time->format('H:i:s');
Note that if you insert that string in a database with a DATETIME column type, it won't work. Mysql will require a string that includes date information.
The code snippet that follows doesn't seem to match with the code you show above:
$data = Excel::selectSheetsByIndex(0)->load($path, function($reader) {
})->get()->toArray();
foreach ($data as $key => $value) {
$time = Carbon::createFromFormat('Y-m-d h:i:s',$value["time"])->format('h:i:s');
print_r($time);
}
You are trying to create a Carbon instance using the createFromFormat() method. The first parameter you provide tells Carbon (actually DateTime) what the format of your input string will be. The data you are supplying is H:i:s (assuming $value["time"] is read from the time column of your Excel sheet), but you're telling Carbon that you will be giving it Y-m-d h:i:s. Since the format you promise doesn't match the data you are giving the object, null is resulting.
Either (broken into to steps for clarity):
$time = Carbon::createFromFormat('H:i:s', $value["time"]);
$timestr = $time->format('h:i:s');
or
$time = Carbon::createFromFormat('d-m-Y H:i:s', $value["date"] . " " . $value["time"]);
$timestr = $time->format('h:i:s');
will work.
The second one gives you a Carbon object that is much more useful - the first one will probably default to year zero. In both cases the timezone will be the zone of the machine the code is running on. You can override that if necessary.
Note that if I'm confused and the Excel reader is actually returning Cabon objects rather than strings, you can eliminate the whole createFromFormat code altogether. No sense making a Carbon object out of a Carbon object.

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;
}

Laravel compare string date in database with carbon date

I have made a mistake by storing the date as VARCHAR in the database and here it looks like 02/12/2018 and I have created a variable using carbon to get the current date +14 days.
$current_date_plus_14 = Carbon::now() -> addDay(14) -> format('d/m/Y');
Problem is
I am trying to compare this date 02/12/2018 which is in the database and stores as VARCHAR to the date that I have generated using Carbon which is 09/04/2017.
Eloquent Code
$gquery = Client::where('required_date', '>=', $current_date_plus_14) -> get();
What I get
It doesn't get any results because it compare only the day in the required_date and the day in the carbon date.
While it should return value because the there is more than 1 year difference?
Try this function that converts date as String (May work with varchar) to a real date
private function convertDateString($date)
{
if (is_string($date)) {
$date = Carbon::parse($date,new DateTimeZone('YOUR_DATE_TIME_ZONE'));
}
return $date;
}
Even if your field is a VARCHAR instead of DATETIME or DATE, you can still mark it as a date in your Eloquent model by adding the attribute name to $dates. You'll also have to change your model's $dateFormat since you have a non-Y-m-d H:i:s format.

Carbon timezone get timestamp

I want to get a real timestamp of given time in specified timezone for using in frontend.
Currently i can set a timezone, and get the time for it. But i can't get a new one timestamp.
Carbon::setToStringFormat('U'); // Set __toString format
$instance = Carbon::createFromTimestamp('1460014482', "Europe/Kiev"); // Set global server timezone (or pickup from default PHP setting)
$instance->setTimezone("Indian/Maldives"); // Set user timezone
var_dump($instance->format('d M Y H:i:s')); // Shows the correct time +2 hours from Europe/Kiev
var_dump((string)$instance); // Shows the same timestamp specified in createFromTimestamp
var_dump(date('d M Y H:i:s', (string)$instance)) // So it won't show the timezone datetime
Explain how i can get a timestamp of time for a given timezone.
Thanks!
You need to use the function createFromFormat to use setTimezone. Here is an example for your code:
$originalDate = date("Y-m-d H:i:s", '1460014482');
$instance = Carbon::createFromFormat('Y-m-d H:i:s', $originalDate, 'Europe/Kiev');
$instance->setTimezone("Indian/Maldives");
Hope it helps.
I know its not a complete solution. But it works for my requirements.
Currently need to override __toString method of Carbon class, which i use to display date timestamp.
public function __toString()
{
return static::$toStringFormat == 'U' ? (string)strtotime($this->format('Y-m-d H:i:s')) : $this->format(static::$toStringFormat);
}

Laravel Carbon Data Missing

In my model I have the following:
protected $dates = [
'start',
'end',
'created_at',
'updated_at'
];
I am using a datetime picker to insert the start and end dates, in this format:
2016-01-23 22:00
Without the seconds. When I do it like this, I get this error:
InvalidArgumentException in Carbon.php line 425:
Data missing
at Carbon::createFromFormat('Y-m-d H:i:s', '2016-01-23 22:00') in Model.php line 3015
If I do include the seconds, it works. The seconds are not important to me, and I do not want to include them in my datetime picker fields. Any way around this so I can still use those fields as date fields?
tl;dr
Your date string and your date format is different, you have to change the format string or modify the date string so they match.
Explanation
The Problem
This error arises when Carbon's createFromFormat function receieves a date string that doesn't match the passed format string. More precisely this comes from the DateTime::createFromFormat function, because Carbon just calls that:
public static function createFromFormat($format, $time, $tz = null)
{
if ($tz !== null) {
$dt = parent::createFromFormat($format, $time, static::safeCreateDateTimeZone($tz));
} else {
$dt = parent::createFromFormat($format, $time); // Where the error happens.
}
if ($dt instanceof DateTime) {
return static::instance($dt);
}
$errors = static::getLastErrors();
throw new InvalidArgumentException(implode(PHP_EOL, $errors['errors'])); // Where the exception was thrown.
}
Not enough data
If your date string is "shorter" than the format string like in this case:
Carbon::createFromFormat('Y-m-d H:i:s', '2017-01-04 00:52');
Carbon will throw:
InvalidArgumentException in Carbon.php line 425:
Data missing
Too much data
If your date string is "longer" than the format string like in this case:
Carbon::createFromFormat('Y-m-d H:i', '2017-01-02 00:27:00');
Carbon will throw:
InvalidArgumentException in Carbon.php line 425:
Trailing data
Under the hood
According to the documentation on mutators the default date format is: 'Y-m-d H:i:s'. The date processing happens in the Model's asDateTime function. In the last condition the getDateFormat function is called, thats where the custom format comes from. The default format is defined in the Database's Grammar class.
Solution
You have to make sure that the date string matches the format string.
Change the format string
You can override the default format string like this:
class Event extends Model {
protected $dateFormat = 'Y-m-d H:i';
}
There is two problem with this approach:
This will apply to every field defined in the model's $dates array.
You have to store the data in this format in the database.
Edit and format the date strings
My recommended solution is that the date format should stay the default 'Y-m-d H:i:s' and you should complete the missing parts of the date, like this:
public function store(Request $request) {
$requestData = $request->all();
$requestData['start_time'] .= ':00';
$requestData['end_time'] .= ':00';
$event = new Event($requestData);
$event->save();
}
And when you want to use the date you should format it:
public function show(Request request, $eventId) {
$event = Event::findOrFail($eventId);
$startTime = $event->start_time->format('Y-m-d H:i');
$endTime = $event->end_time->format('Y-m-d H:i');
}
Of course the fields should be mutated to dates:
class Event extends Model {
protected $dates = [
'start_time',
'end_time',
'created_at',
'updated_at',
'deleted_at',
];
}
Models
This function disabled, the emulations for carbon in Datetimes
https://laravel.com/docs/5.0/eloquent#date-mutators
public function getDates()
{
return [];
}
You can set the $dateFormat in your model as Christian says, but if you don't want to imply the updated_at and created_at fields into the operation you can use events to "correct" the datetime object before saving it into the database.
Here you have the official doc about it: https://laravel.com/docs/5.2/eloquent#events
You need to set protected $dateFormat to 'Y-m-d H:i' in your model, see https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
Make sure you are not omitting the "created_at" or "updated_at" fields in some rows in your database, which are required; if that is the case delete the records where they have those empty fields or enter a value in the valid timestamp format, example '2018-09-01 15:18:53'.
This is one possibility
You need to check the column of resultant data. If your column name 'created_at' or 'updated_at' is null, then it will through this error.
How to Solve ?
First of all, you need to store the data in those two columns using Laravel carbon.
Eg:
$user = new User();
$user->created_at = Carbon::now()->setTime(0,0)->format('Y-m-d H:i:s');
$user->updated_at = Carbon::now()->setTime(0,0)->format('Y-m-d H:i:s');
$user->save();
That's All, I hope it will work
Happy Coding....
For me the problem was with SQLServerGrammar located into the vendor (vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\SqlServerGrammar.php).
Default in SQLServerGramma is Y-m-d H:i:s.v.
We extended the class end removed .v.

Categories