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

如何在Ruby中将十进制年份值转换为日期?,ruby,datetime,Ruby,Datetime,输入: 2015.0596924 期望输出: 2015年1月22日 这是我想到的 # @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

输入:

2015.0596924

期望输出:

2015年1月22日


这是我想到的

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

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

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"
需要“日期”
d=2015.0596924
年份=日期。新(d)
#=> # 
日期=(年+(year.leap?366:365)*(d%1))
#=> # 
日期.strftime(“%B%d,%Y”)
#=>“2015年1月22日”

在发布答案之前,您是否已经知道答案?”因为你不到一分钟就回答了自己的问题minute@DyrandzFamador当然,他是这样做的,但这种情况经常发生。我看不出有什么问题。是的,我一直在研究一些其他的想法,主要是,但我没有看到一个地方有代码来准确地得到正确的一天。只需在此处发布,以便下一个人可以使用它,你们都可以取笑我的代码。@DyrandzFamador当您提出问题时,可以选择“回答您自己的问题-分享您的知识,问答式”。我只是使用了它,尽管我知道它不是最有效的解决方案(我在这方面被证明是非常正确的)@AlienLifeForm,是的,这没有问题。Jon skeet也这样做是为了分享他的知识。:)事实上,我看没问题,我问这个问题只是为了确认你是否已经知道答案这比我(下面)做的要容易得多。不好意思,谢谢。没必要不好意思,因为我们都需要从某个地方开始。我可以从您对camel-case变量名的选择中看出(Ruby约定是snake-case,用于
变量和方法),您对Ruby是相当陌生的。这可能还意味着你还有一些未学的东西要做。谢谢@CarySwoveland,也许你也可以在这里改进我的Javascript版本:“Javascript”?从没听说过。跟咖啡有关吗?。我现在的曲目是Ruby,没有Rails。