Rails 格式化日期 [英] Rails formatting date

查看:44
本文介绍了Rails 格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我向 API 发布日期,所需格式如下:

I am posting a date to an API and the required format is as follows:

2014-12-01T01:29:18

我可以像这样从模型中获取日期:

I can get the date from the model like so:

Model.created_at.to_s

返回:

2014-12-01 01:29:18 -0500

如何使用 Rails 或 Ruby 将其格式化为所需的格式并使用 T 并删除 -0500?

How can I use Rails or Ruby to format it like the required format with the T and removing the -0500?

推荐答案

使用

Model.created_at.strftime("%FT%T")

哪里,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

以下是您可以在 strftime 方法中指定的一些常用的有用的 DateTime 格式列表:

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

有关strftime 方法格式的完整列表,请访问APIDock

For the complete list of formats for strftime method please visit APIDock

这篇关于Rails 格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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