How to save date in Laravel in GMT 0? - laravel

How to save date in GTM 0 in database?
I mean this: protected $dates = ['created_at'];

I'd personally recommend leaving/setting the timezone in your app config as UTC rather than GMT:
https://www.timeanddate.com/time/gmt-utc-time.html
To make sure my custom date fields are stored correctly I use a modifier on my model class like so:
public function setStartAtAttribute($date)
{
$timezone = (Auth::check() ? Auth::user()->profile->timezone : config('pgn.phoenix.timezone'));
$tzdate = Carbon::createFromFormat('d/m/Y H:i', $date, $timezone);
$this->attributes['start_at'] = $tzdate->timezone('UTC');
}
That would need use Carbon\Carbon; adding to the top of your model too.
That config param above is set to 'Europe/London' and is the timezone that our guests are shown dates, (works with daylight savings) whilst not affecting the 'system' timezone.

You can change the timezone of the application by going to the config/app.php file and changinf the following line:
'timezone' => 'GMT'
If your dates are still saved in a different timezone, it is likely that the server datetime will need to be altered to GMT. This can be done using the following command and following the instructions:
dpkg-reconfigure tzdata

Related

Laravel discrepancy between two date fields that should both be UTC

I'm on a project that uses Laravel 8.
My timezone is configured as such in my config/app.php file:
'timezone' => 'UTC',
My migration is setup like this:
$table->dateTimeTz('sent_at')->nullable();
$table->timestampsTz();
And when I create a new record for this table I do something like this:
$model = Model::create([
'sent_at' => now(),
]);
Yet when I inspect the database, or when I display the dates in Laravel Nova for example, it seems like the created_at is stored/displayed in UTC but not the sent_at. They should be identical?
I end up with:
created_at: 2022-07-02 07:29:59
sent_at: 2022-07-02 10:29:59
What am I doing wrong? I'd like both these fields to be identical.
You can get current time and date of timezone UTC using bellow lines:
$date = new DateTime("now", new DateTimeZone('UTC') );
echo $date->format('Y-m-d H:i:s');
Please check same question on stackoverflow Laravel changing timezone not reflecting the correct time

Laravel - different formats for date/time query

I am learning Laravel and I have some small problem on controllers - when I use DB, the query returns date time without timezone but if I use model, the query returns full datetime.
public function test($switch)
{
//return "YYYY-MM-DDThh:mm:ss.000000Z"
if ($switch) return Position::select('id','created_at')->orderBy('id')->get();
// return "YYYY-MM-DD hh:mm:ss"
return DB::table('positions')->select('id','created_at')->orderBy('id')->get();
}
Why? What I need to dof I want "YYYY-MM-DDThh:mm:ss.000000Z" on both cases?
Thanks for solution.
thanks for advice
You should use the DB::raw
The following statement will convert the datetime value created_at from +00:00 timezone to +10:00 timezone.
You can try this
return DB::table('positions')->select(DB::raw('id',CONVERT_TZ('created_at','+00:00','+10:00'))->orderBy('id')->get();
you can set your timezone that you wants to convert it
They are the same data, probably just different classes of date and you can always format your date. Laravel utilizes Carbon date library which is excellent and should be used primarily.
If you try to print out your date class with get_class() for Eloquent Position created_at, you probably got Carbon and DB::table('positions') created_at, you probably got DateTime and that's why the value looks different (but you still got the same date).
If you want to convert your DateTime to Carbon, you can do
$newDate = new \Carbon\Carbon($position->created_at)
Thanks Anurat,
I realized this fact shortly after sending the previous question.
... but there is another 'issue' - both times are my local time - time in "YYYY-MM-DDThh:mm:ss.000000Z" is not UTC time as I expected.
I changed my function:
public function test($switch = false)
{
$data = Position::selectRaw('id, created_at, UNIX_TIMESTAMP(created_at) unix')->orderBy('id')->get();
foreach ($data as $d) {
$conv = new \DateTime($d->created_at);
$d->conv = intval($conv->format('U'));
$d->diff = $d->conv - $d->unix;
}
return $data;
}
... and result is
0
id 1
created_at "2021-03-18T12:36:59.000000Z"
unix 1616067419
conv 1616071019
diff 3600
As you see, the difference is 1 hour (as my timezone offset). Where is a problem?
Thanks.

Laravel: Check if time + 4 hours has passed

I store in my database a date format like this:
2017-02-22 16:55:40
I added it to my database like this:
Carbon::now();
I need to check if 4 hours passed since this date.
How I can do this? I couldn't figure out how I can convert this format into Carbon or timestamp.
If you are using Laravel and the date is a Carbon instance from a Model you have access to the whole Carbon API.
You can use the Difference API of Carbon for this specific purpose.
echo $model->thedate->diffInHours($now, false);
If your model does not threat the date as a carbon instance you can cast it by adding the date to the dates array of the current model like so
protected $dates = [
'field_name',
];
Check out Date casting for more information
Update with an explicit example
$user = User::first();
// This will return the difference in hours
$user->created_at->diffInHours(Carbon\Carbon::now(), false);
You can convert it to a Carbon object with:
Carbon::parse('2017-02-22 16:55:40');

Laravel 5 get current datetime in MySQL format

In Laravel 5, how to get current DateTime in local time (without timezoning) and convert it to MySQL datetime?
use Carbon\Carbon
$mytime =Carbon::now();
echo $mytime->toDateTimeString();
see this
Carbon
For current time you in your local timezone you can use carbon in laravel
Carbon::now('Asia/Dhaka')->toDateTimeString()
and you can use it in mysql.To get timezone list go here http://php.net/manual/en/timezones.asia.php
If you are using Laravel 5.2 and want to change MySQL timezone, you'll have to edit config/database.php and add this line
'mysql' => [
...
'timezone' => '+01:00'
],
To set current DateTime in your local time for your application, go to config/app.php, find timezone end replace 'UTC' to 'Asia/Dhaka'.

How to set model attribute to current date format using MySQL functions?

I have a model Users And every time user logges in loggedin_at field is updated.
$user = User::find(1);
$user->token = md5(time());
$user->loggedin_at = date('Y-d-m H:i:s');
$user->save();
return $user;
But I know from experience already that sometimes there is difference between MySQL time and PHP time. So when you use comparisons like time > NOW() - INTERVAL 1 HOUR it might now work correctly because you set date from PHP and compare it from MySQL.
Anyway my question is I want to use NOW() to update my date. I try
$user->loggedin_at = DB::raw('NOW()');
But that does not work. By looking into Eloquent source I've managed out this to work
$user->loggedin_at = new \Carbon\Carbon();
This is what Eloquent uses to alter times.
How to use NOW() to set time?
Should I use NOW() or better continue with Carbon?
It's better to use Carbon, it's what it's there for. Laravel uses it out of the box, and uses it within created_at and updated_at.
If you use Carbon, also, you can synchronize PHP's time and Carbon's "NOW" using the timezone configuration inside of config/app.php.
Furthermore, if you want to change the result you get from Carbon, you can do something like:
$now = Carbon::now(new DateTimeZone('Europe/London'));
//can also be passed as a string
$now = Carbon::now('Europe/London');

Resources