在 Ruby on Rails 中,如何使用“th"来格式化日期?后缀,如“Sun Oct 5th"? [英] In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"?

查看:30
本文介绍了在 Ruby on Rails 中,如何使用“th"来格式化日期?后缀,如“Sun Oct 5th"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以以下格式显示日期:短星期几、短月份、不带前导零但包括th"、st"、nd"或rd"后缀的月份日期.

I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix.

例如,提出此问题的日期将显示Thu Oct 2nd".

For example, the day this question was asked would display "Thu Oct 2nd".

我使用的是 Ruby 1.8.7 和 Time.strftime 似乎没有这样做.如果存在标准库,我更喜欢标准库.

I'm using Ruby 1.8.7, and Time.strftime just doesn't seem to do this. I'd prefer a standard library if one exists.

推荐答案

使用 'active_support' 中的 ordinalize 方法.

Use the ordinalize method from 'active_support'.

>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"

注意,如果你在 Ruby 2.0 中使用 IRB,你必须先运行:

Note, if you are using IRB with Ruby 2.0, you must first run:

require 'active_support/core_ext/integer/inflections'

这篇关于在 Ruby on Rails 中,如何使用“th"来格式化日期?后缀,如“Sun Oct 5th"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆