1

目前,当我将模型转换为 JSON 时,所有 Carbon 日期字段都像这样转换:

"end_time": {
    "date": "2017-02-03 23:59:00.000000",
    "timezone_type": 3,
    "timezone": "Europe/London"
}

我希望它使用Atom符号进行转换。这可以在碳中完成,如下所示:

$order->end_time->toAtomString()

$date日期在哪里Carbon

将模型转换为 JSON 时,如何使模型以 atom 格式转换日期?

我知道可以像这样附加数据:https ://laravel.com/docs/5.3/eloquent-serialization#appending-values-to-json

但这不会改变现有值的格式吗?

4

3 回答 3

3

冒着复活僵尸的风险,我将提出这个问题的另一种解决方案:

覆盖serializeDatetrait 定义的方法HasAttributes

/**
 * Prepare a date for array / JSON serialization.
 *
 * @param  \DateTimeInterface  $date
 * @return string
 */
protected function serializeDate(DateTimeInterface $date)
{
    return $date->toAtomString();
}
于 2017-08-29T17:38:10.323 回答
1

只要您愿意使用与“end_time”不同的名称,您提供的链接就应该是您的解决方案。您可以附加“end_time_formatted”或类似的内容。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{

    protected $appends = ['end_time_formatted'];

    public function getEndTimeFormattedAttribute()
    {
        return $this->end_time->toAtomString();
    }
}

然后,每当您将模型转换为 json 时,它都会包含“end_time_formatted”。

您的另一个选择(如果您需要保持相同的名称)是通过将 toJson 方法复制到您的模型中来覆盖它。我可能会建议不要这样做,但它会避免$this->created_at = $this->created_at->toAtomString()每次在将其转换为 JSON 之前都需要说明。

/**
     * Convert the model instance to JSON.
     *
     * @param  int  $options
     * @return string
     *
     * @throws \Illuminate\Database\Eloquent\JsonEncodingException
     */
    public function toJson($options = 0)
    {
        $atom = $this->created_at->toAtomString();
        $json = json_encode($this->jsonSerialize(), $options);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw JsonEncodingException::forModel($this, json_last_error_msg());
        }
        $json = json_decode($json);
        $json->created_at = $atom;
        $json = json_encode($json);

        return $json;
    }

我无法通过更改方法顶部的值来使其工作,所以我被迫 json_decode,然后重新编码,这对我来说感觉不太好。如果您确实使用这条路线,我建议您深入挖掘以尝试使其工作而无需解码。

于 2017-02-03T19:32:15.217 回答
-1

另一种使用方法是格式化您从模型收到的日期

您可以使用辅助方法将您的日期对象转换为您希望使用碳的格式。

碳有助于格式化能力,我觉得这就是你要找的:

your_function_name($created_at_date, $format = "jS M Y") 
 {
    $carbon = new \Carbon\Carbon($created_at_date);
    $formatted_date = $carbon->format($format);

    return $formatted_date;
  }

希望这可以帮助。

于 2017-02-04T12:46:43.830 回答