laravel mysql 时区_在Laravel中将默认数据库DateFormat设置为具有时区的ISO 8601

在Laravel应用中,要将Eloquent模型的默认DateTime格式设置为ISO 8601并包含时区,可以创建一个扩展Eloquent的mEloquent类,并重写getDateFormat方法。迁移文件中的表创建可保持不变,如正常使用timestamps()。通过Carbon对象,可以在模型中创建一个访问器,将日期转换为ISO 8601格式,例如`getPublishedAt8601Attribute`方法,然后通过`$post->published_at_8601`来访问带时区的ISO 8601日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bd96500e110b49cbb3cd949968f18be7.png

I think the title says it: I want to use ISO 8601 with timezones as default DateTime-Format in Laravels Eloquent. I got this

class mEloquent extends Eloquent {

protected function getDateFormat()

{

return 'YYYY-MM-DDThh:mm:ss.sTZD';

}

}

All my models will extend mEloquent. But how should I build the tables? Just

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

class CreateUsersTable extends Migration {

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('users', function(Blueprint $table)

{

$table->increments('id');

$table->string('firstName');

$table->string('lastName');

$table->string('email')->unique();

$table->string('password');

$table->timestamps();

});

} ......

as normal?

How can I compare this dateformat? Or shoud I just use the default one and save the timezone separately?

解决方案

It’s really easy if you follow the documents.

PHP date function supports ISO 8601 since PHP5 and we can get it by passing the 'c' format character.

Laravel model converts date attributes to Carbon objects. Carbon extends DateTime which has the format function that supports all of the date format characters.

You can easily create an accessor (or even a new custom attribute) to change a date attribute. Then use the Carbon format method to change it to ISO 8601 format.

So in a laravel model, we can do something like this:

public function getPublishedAt8601Attribute()

{

return $this->published_at->format('c');

}

and then we can access the attribute like this:

// Prints something like: 2016-10-13T21:48:00+03:00

echo $post->published_at_8601;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值