Laravel timestamp saving time as unix timestamp - laravel

I was wondering what would be the easiest way to change in laravel to save timestamps in database as unix valid timestamp?
Thanks in advance!

Please read about Laravel date mutators:
https://laravel.com/docs/5.1/eloquent-mutators#date-mutators
By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to
customize the timestamp format, set the $dateFormat property on your
model. This property determines how date attributes are stored in the
database, as well as their format when the model is serialized to an
array or JSON
Also, you can override getDateFormat():
protected function getDateFormat()
{
return 'U';
}
And use this in your migration files:
$table->integer('updated_at');
$table->integer('created_at');
And, if you use soft deletes:
$table->integer('deleted_at');
https://laravel.com/docs/4.2/eloquent#timestamps

Related

Using time field in Eloquent model

I have got a database field containing only a time, it's declared in my migration as
$table->time('time')->default('00:00:00');
Now I want to add a number of seconds to this field using Eloquent, doing something like:
$activetime->time->add(new DateInterval('PT5S'));
(where $activetime is a object of a Eloquent model)
First try on this I got
Call to a member function add() on string
So obviously I have to tell Eloquent that this is not a string but a time. The closest I have got is putting it in protected $dates in the model, but then instead I get
Unexpected data found.
I suspect this is because it isn't really a date but only a time, but I can't seem to find much information about how to handle times. Is there any way of solving this or would I be better off using something else, like dateTime or timestamp (or even an integer for amount of seconds)? What I DO want to record is a users amount of active time for a given date, so for that purpose time seems like the natural choice...
This is because Laravel reads time database type as just a string and you are expecting a DateTime Object.
Add this to your Eloquent model:
public function getTimeAttribute($value)
{
return new \DateTime($value);
}
You can also cast your time to DateTime Object using Laravel Attribute Casting, but you'll have to append some date to your time, because Laravel is expecting correct format

Laravel - What's the difference between timestamp() and timestampTz()?

What's the difference between timestamps() and timestampsTz() methods in the Laravel's Schema Builder? I tried searching google but couldn't find any help.
Basicly timestampsTz() stands for Timestamp with Timezone while timestamps() is like Timestamp without timezone
TimestampsTz() is a representation for a specific point in time. The adjustment to this time is made by the timezone that is related to your system.
The normal timestamps() is more a representation like normal clock.
Have a look at this example:
If you are using the timestamps() function you will also store the timezone that was chosen by your environment. If you are using the timestampsTz() you will not safe the timezone.
I guess it would be good practice to use timestamp without timezone when all your data is for sure in the same zone, or you got another layer over there which handles the time conversion.
Update:
In the Database the normal timestamps() will look like
2004-10-19 10:23:54
while the timestampsTz() looks like
2004-10-19 10:23:54+02
Update 2:
These functions are in Laravel available for every type of Database. But this only differs for PostgreSQL. Have a look at the docs: PostgreSQL Timestamp. In the other databases the timezone information is included in the timestamp automatically.
In all other databases this will have the same output.
timestampsTz() = Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
timestamps() = Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
The difference is that timestampsTz() adds a timezone.

Can't remove hours and minutes from datatable

I'm trying to get release date field with y-m-d format.. Actually time format (for y-m-d) seems fine but also it gives h:m:s too, I changed time format at server side and removed h:m:s but datatable still shows them
What I get
2012-04-11 00:00:00
What I want
2012-04-11
Released_at field (Metronic theme - json datatable)
{
field: "released_at",
title: "Release Date",
type: "date",
format: "YYYY/MM/DD"
}
time format (I'm using laravel framework)
protected $dateFormat = "Y-m-d";
How do I fix this ?
Datatable accept column type same as mysql type.
You are trying to convert mysql dateTime column to Date in datatable, which is not possible from datatable.
In your code you have declared
format: "YYYY/MM/DD" // but actual type is dateTime as per mysql.So it will append time next to it.
If you are storing only date in mysql then you can change column type to Date, and your problem gets solved.
And if you want to convert string to date in laravel you can follow this post.
Your database column is of type dateTime which, by definition, includes both date and time information. If you want to remove the time at a database level then use the date type instead
$table->date("released_at")->nullable();
If instead of removing the time from the database, you just want to ignore it for certain parts of your application, you can leverage the fact than in Laravel all dates coming from your models are Carbon\Carbon instances, so you could do
$model->releasedAt->format('y-m-d'); // Returns '18-09-11'

What does $dateFormat variable actually do in Laravel Model?

I can't see any difference if I set this variable or not.
I need some basic example
if this variable is set:
protected $dateFormat = "d.m.Y H:i";
What difference does it make???
P.S. I have already read about in Docu but it's not clear where is this date format actually used??
https://laravel.com/docs/5.5/eloquent-mutators#date-mutators
Update
Using jQuery datetimepicker localized so the date that gets saved is in this format: "25.09.2017 08:04"
changed the column data type in migration from timestamp to dateTime.
changed timezone in config/app.php to: 'timezone' => 'Europe/Berlin',
set the variable to:
protected $dateFormat = "d.m.Y H:i";
And I get an error on form submit:
and if I the variable is NOT set
I get this error:
TL;DR: Your $dateFormat is used to both parse incoming post data, and format data sent to your database. This means that, without any other code (read: setter that overrides this), your UI must use the same datetime format as your database.
The $dateFormat is used by HasAttributes::asDateTime to parse incoming strings into Carbon objects. This method is used in many places to handle automatic casting of the attributes into proper data types. This includes both the $casts array and the $dates array.
One common invocation is via Model::fill(...) > HasAttributes::setAttribute(...) > HasAttributes::fromDateTime(...). Note that Model::__set(...) also calls into HasAttributes::setAttribute(...). This means that the $dateFormat is used to parse incoming string values from [presumed] form posts when you use mass-assignment/fillable, or when you set attributes directly using $model->myField = ...;. You're expected to set the format to what the browsers are posting so the values can be properly parsed into Carbon objects.
The Carbon objects are then serialised back into strings in HasAttributes::fromDateTime(...) which means that Laravel handles your datetime values as strings, which surprised me when researching this. This means that your $attributes array contains string representation of your datetime values, and these string values are sent to the database.
This means that $dateFormat needs to produce a string value supported by your database.
Keep in mind that this is the format of the datetime value when submitted, not shown. The datetime-local html5 datatype, for example, will use the local locale when formatting the datetime, but will always post the value in a specified format.
One thing to note is that the displayed date format differs from the actual value — the displayed date format will be chosen based on the set locale of the user's operating system, whereas the date value is always formatted yyyy-MM-ddThh:mm.
Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local
That is the format how it is saved in the database.

Laravel PHPExcel convert date into double

I've tried to import an excel file with a column formated DATE by PHPExcel with Laravel 5.4. PHPExcel read the file and output date into double number. The date() function of PHP cannot convert into date for importing into database.
Is there anybody get the same issue?
Update: this is my code
Excel::filter('chunk')
->selectSheetsByIndex(1)
->load(config('excel.import.storage').$fileName)
->chunk(1000, function($rows) {
foreach ($rows as $i=>$row) {
dd($row->toArray());
}
});
The date in excel column is 03/03/2017. The output is 42797.0 So, the date() function cannot work.
Internally, MS Excel stores dates as a float/double, a serialized timetamp (similar to a Unix timestamp, but counting the number of days rather than seconds, and with a different base date). I'm not familiar enough with the Maatwebsite wrapper for laravel to explain why ->formatDates(true) isn't converting that timestamp to a formatted date/time, but PHPExcel does provide native functionality for converting between Excel timestamps and formatted date/times (or indeed to unix timesstamps or DateTime objects in the \PHPExcel_Shared_Date class.
Thanks guys for your comments. I find myself the answer which is easier than I think. You consider the code below to import the Excel files have date columns.
Excel::selectSheetsByIndex(1)
->load(config('excel.import.storage').$fileName, function ($reader){
$rows = $reader->all();
dd($rows[0]->ngay->format('Y-m-d'));
});
The result will be printed as your format string d-m-Y, m-d-Y, ...

Resources