2

Hello Drupal community.

I have a “Product” content type with field_alert_date field.
The field date type is “Date only” so when I get jsonapi response
by accessing jsonapi/node/product I have the following output for this field:

"field_alert_date":"2020-02-22"

However, this response will be used by another program
and that program requires data in the following format:

"field_alert_date":"2020-02-22 0:00:00”

So I need to modify the jsonapi output to add “0:00:00” (or another time) without changing the field data type.
The program is not developed by me so I cannot change this requirement. I have to do something with the output of the jsonapi.

Could you please tell me if it is possible and how it can be implemented?

| improve this question | | | | |
3

You can change the JSON output of a date field by implementing a custom Normalizer for date fields in a custom module. I got it to work using the following code. This is a bit of a hatchet job, so you'll want to clean up and stuff, but otherwise it should do the job:

/src/Normalizer/DateTimeCustomNormalizer.php:

<?php

namespace Drupal\custom_date_serializer\Normalizer;

use Drupal\serialization\Normalizer\DateTimeIso8601Normalizer;

/**
 * @internal
 */
class DateTimeCustomNormalizer extends DateTimeIso8601Normalizer {

  /**
   * {@inheritdoc}
   */
  protected $allowedFormats = [
    'RFC 3339' => \DateTime::RFC3339,
    'ISO 8601' => \DateTime::ISO8601,
    // used to be 'Y-m-d', so you can use any PHP date format you want
    // I just set it to this because it was easy to test
    'date-only' => \DateTime::ISO8601, 
  ];
}

And /custom_date_serializer.services.yml:

services:
  custom_date_serializer.normalizer.datetimecustom:
    class: \Drupal\custom_date_serializer\Normalizer\DateTimeCustomNormalizer
    arguments: ['@config.factory']
    tags:
      # Priority must be higher than other datetime normalizers.
      - { name: normalizer, priority: 40 }

And you'll need an info.yml obviously.

| improve this answer | | | | |
  • Thank you. I will try it. – Sergey Feb 3 at 1:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.