Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 Ruby Cookbook | 日付のフォーマット

パンくず

Ruby Cookbook
日付のフォーマット

概要

日付のフォーマット

フォーマット表

フォーマット用文字 内容
%A English day of the week
%a Abbreviated English day of the week
%B English month of the year
%b English month of the year
%C The century part of the year, zero-padded if necessary.
%d Day of the month, zero-padded
%e Day of the month, not zero-padded
%F Short date format with 4-digit year.; equivalent to
%G Commercial year with century, zero-padded to a minimum of four digits and with a minus sign prepended for dates BCE (seeRecipe 3.11. For the calendar year, use %Y)
%g Year without century, zero-padded to two digits
%H Hour of the day, 24-hour clock, zero-padded to two digits
%h Abbreviated month of the year; the same as
%I Hour of the day, 12-hour clock, zero-padded to two digits
%j Julian day of the year, padded to three digits (from 001 to 366)
%k Hour of the day, 24-hour clock, not zero-padded; like %H but with no padding
%l Hour of the day, 12-hour clock, not zero-padded; like %I but with no padding
%M Minute of the hour, padded to two digits
%m Month of the year, padded to two digits
%n A newline; don't use this; just put a newline in the formatting string
%P Lowercase meridian indicator (
%p Upper meridian indicator. Like %P, except gives
%R Short 24-hour time format; equivalent to
%r Long 12-hour time format; equivalent to
%S Second of the minute, zero-padded to two digits
%s Seconds since the Unix epoch
%T Long 24-hour time format; equivalent to
%t A tab; don't use this; just put a tab in the formatting string
%U Calendar week number of the year: assumes that the first week of the year starts on the first Sunday; if a date comes before the first Sunday of the year, it's counted as part of
%u Commercial weekday of the year, from 1 to 7, with Monday being day 1
%V Commercial week number of the year (see Recipe 3.11)
%W The same as %V, but if a date is before the first Monday of the year, it's counted as part of
%w Calendar day of the week, from 0 to 6, with Sunday being day 0
%X Preferred representation for the time; equivalent to
%x Preferred representation for the date; equivalent to
%Y Year with century, zero-padded to four digits and with a minus sign prepended for datesBCE
%y Year without century, zero-padded to two digits
%Z The timezone abbreviation (Time) or GMT offset (Date). Date will use for Date
%z The timezone as a GMT offset
%% A literal percent sign
%v European-style date format with month abbreviation; equivalent to
%+ Prints a Dateobject as though it were a Timeobject converted to a string; like %c, but includes the timezone information; equivalent to

サンプル

require 'date'

now = "2012/12/12"
puts Date.parse(now).to_s

puts Date.strptime("2003年04月18日", "%Y年%m月%d日").to_s

now = "2012年12月12日"
date_format ="%Y年%m月%d日"
puts Date.strptime(now, date_format).to_s

puts DateTime.now.strftime(date_format)

出力

2012-12-12
2003-04-18
2012-12-12
20120619