Convert date format in Serializer

I am displaying my data like this.. Can someone suggest a way to display the last date as February 02,2023 using serializer?

"category": {
          "data": {
          "id": "81",
          "attributes": {
                  "id": 81,
                  "name": "ggg",
                  "last_date": "2023-02-22",
                  "created_at": "2023-02-15T13:01:53.341+05:30",
                  "updated_at": "2023-02-15T13:01:53.341+05:30",
                  }
              }
       }

I have tried adding below in my serializer.. but it is not working

attribute :last_date do |object|
      object.last_date&.to_s(:date)
end

>Solution :

I would use strftime like this:

attribute :last_date do |object|
  object.last_date&.strftime('%B %e, %Y')
end

When you use the same format at other places in your application too, then you might want to give it a proper name in

# config/initializers/time_formats.rb
Time::DATE_FORMATS[:us_date_format] = '%B %e, %Y'

Which would allow you to use this format with to_fs like this in your app:

attribute :last_date do |object|
  object.last_date&.to_fs(:us_date_format)
end

Leave a Reply