DavisThom09
DavisThom09

Reputation: 11

Rails convert datetime to date

I just need 1 instance where I have a date field instead of a datetime field. No need in creating a new column just for 1 date.

How do I convert datetime to date when displaying data?

HTML that needs converting;

<td> <%= product.pDate %> </td>

Upvotes: 0

Views: 996

Answers (2)

ScottM
ScottM

Reputation: 10414

There are actually a number of approaches you can take in Rails. Link Nguyen's answer is the pure Ruby approach, which works here and would also work in other Ruby contexts outside of Rails.

Rails also adds #to_formatted_s and #to_s (they're aliases of one another) to the date and time objects, e.g.:

<%= product.pDate.to_s(:long) %>

Rails define some date formats by default, and you can add your own by adding values to the Date::DATE_FORMATS array in an initializer (see the docs for examples).

A additional, slightly newer approach uses the locale files (e.g., config/locales/en.yml) to define formats, which can then be accessed in your views using the l (for localize) helper:

# Your ERb file
<%= l product.pDate, format: :short %>

# Your configs/locale/xx.yml file
# NB: `short` is defined by default but you can redefine it if you want

en:
  date:
    formats:
      short: "%m/%d/%y"

See the Rails i18n guide for more.

The advantage of both Rails approaches is that you can decide on a standard style, or collection of standard styles, that you apply to dates/times everywhere in your app. If you were to decide to switch from two-digit years to four, or vice versa, the strftime approach would require editing every view (and not missing any), but with either Date#to_s or l() you change the configuration format in one place. The i18n approach allows you to further customise date formats for international markets if you want to (for example, day/month/year is an almost exclusively US ordering, so you might want to use a different format for other languages).

Upvotes: 2

Linh Nguyen
Linh Nguyen

Reputation: 947

You can try strftime. for example product.strftime("%m/%d/%Y")

Upvotes: 1

Related Questions