输入:
2015.0596924
期望的输出:
2015年1月22日
答案 0 :(得分:2)
您可以按如下方式获取格式化日期:
require 'date'
d = 2015.0596924
year = Date.new(d)
#=> #<Date: 2015-01-01 ((2457024j,0s,0n),+0s,2299161j)>
date = (year + (year.leap? ? 366 : 365) * (d % 1))
#=> #<Date: 2015-01-22 ((2457045j,68059s,526396957n),+0s,2299161j)>
date.strftime("%B %d, %Y")
#=> "January 22, 2015"
答案 1 :(得分:0)
这就是我想出来的。
# @param decimalDate [String] the date in decimal form, but can be a String or a Float
# @return [DateTime] the converted date
def decimal_year_to_datetime(decimalDate)
decimalDate = decimalDate.to_f
year = decimalDate.to_i # Get just the integer part for the year
daysPerYear = leap?(year) ? 366 : 365 # Set days per year based on leap year or not
decimalYear = decimalDate - year # A decimal representing portion of the year left
dayOfYear = (decimalYear * daysPerYear).ceil # day of Year: 1 to 355 (or 366)
md = getMonthAndDayFromDayOfYear(dayOfYear, year)
DateTime.new(year,md[:month],md[:day])
end
# @param dayOfYear [Integer] the date in decimal form
# @return [Object] month and day in an object
def getMonthAndDayFromDayOfYear(dayOfYear, year)
daysInMonthArray = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
daysInMonthArray[2] = 29 if leap?(year)
daysLeft = dayOfYear
month = 0
daysInMonthArray.each do |daysInThisMonth|
if daysLeft > daysInThisMonth
month += 1
daysLeft -= daysInThisMonth
else
break
end
end
return { month: month, day: daysLeft }
end
# @param year [Integer]
# @return [Boolean] is this year a leap year?
def leap?(year)
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0
end