Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading