如何将十进制年份值转换为Ruby中的日期?

输入:

2015.0596924

期望的输出:

2015年1月22日

您可以按如下方式获取格式化日期:

require 'date' d = 2015.0596924 year = Date.new(d) #=> # date = (year + (year.leap? ? 366 : 365) * (d % 1)) #=> # date.strftime("%B %d, %Y") #=> "January 22, 2015" 

这就是我想出的。

 # @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