【问题标题】:How do I format a date to mm/dd/yyyy in Ruby?如何在 Ruby 中将日期格式化为 mm/dd/yyyy?
【发布时间】:2010-11-16 20:21:57
【问题描述】:

在 Perl 中你可以这样做:

my $current_time = DateTime->now();
my $mdy = $current_time->mdy("/");

在 Ruby 中最简单的方法是什么?

【问题讨论】:

  • 对于它的价值,如果你想在 Perl 中做这件事(即,你不再需要 DateTime),我认为使用 Perl 中的 strftime 函数更容易POSIX 模块。更多信息请看这里:perltraining.com.au/tips/2009-02-26.html.

标签: ruby time


【解决方案1】:
my $current_time = DateTime->now();

my_current_time = DateTime.now

my $mdy = $current_time->mdy("/");

my_mdy = my_current_time.strftime("%m/%d/%Y")

【讨论】:

    【解决方案2】:

    您可以简单地将%Dstrftime 方法一起使用

     > Time.now.strftime("%D")
     => "11/24/14"  # mm/dd/yy
    

    【讨论】:

      【解决方案3】:

      strftime 方法可用于格式化时间:

      Time.now.strftime("%m/%d/%Y")
      

      【讨论】:

      • +1 但是请注意,strftime 在 Perl 中也可用,search.cpan.org/perldoc/DateTime 有很多功能超出了这里的简单示例。
      • strftime 是实现这些格式字符串的底层 C 库的名称。这是此特定日期格式的所有语言的标准名称。
      • @mpeters - 仅仅因为它是标准的并不意味着它是好的。命名creat() 结尾不带e 只是一个可怕的设计错误,而用strftime() 之类的名称命名函数同样糟糕。我们可以看到为什么它在过去发生,但在现在它是可怕的。
      • 注意: 这是 mm/dd/yy。 对于 mm/dd/yyyy,请使用 Time.now.strftime("%m/%d/%Y") ( %Y).
      【解决方案4】:

      我写了一个 gem 来帮助格式化日期,并保持你的视图干燥(不必每次你想格式化日期时都 strftime)。

      查看:http://github.com/platform45/easy_dates

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-01
        • 2013-03-18
        • 1970-01-01
        • 2021-04-19
        • 1970-01-01
        • 2020-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多