我正在收集用户输入为“DD / MM / YYYY”
目标是以csv YYYY,MM,DD传入mktime。
puts "Please enter dob in dd/mm/yyyy format;"
inp = gets.chomp
inp = inp.gsub(" ","")
while inp.length != 10
puts "Please use dd/mm/yyyy format"
inp = gets.chomp
end
bday = inp.gsub("/",",")
ctime = Time.new
btime = Time.mktime(bday)
lsecs = ctime - btime
ysecs = Time.mktime(2001) - Time.mktime(2000)
rsecs = 1000000000 - lsecs
ryears = rsecs / ysecs
puts "You are currently #{lsecs} seconds old"
puts "You have #{ryears} years until you are a billion seconds old!!"
正如您所看到的,剩下的唯一任务是撤消用户输入,无法找到紧凑的解决方案。如果你有办法,请随意帮助缩短这段代码。
解决方案: (秒数和年份四舍五入/分隔)
def reformat_date(str)
str.split("/").reverse.join(",")
end
puts "Please enter dob in dd/mm/yyyy format;"
inp = gets.chomp
inp = inp.gsub(" ","")
while inp.length != 10
puts "Please use dd/mm/yyyy format"
inp = gets.chomp
inp = inp.gsub(" ","")
end
ctime = Time.new
btime = Time.mktime(reformat_date(inp))
lsecs = ctime - btime
**lsecdel = lsecs.round(0).to_s.reverse.gsub(/...(?=.)/,'\&,').reverse**
ysecs = Time.mktime(2001) - Time.mktime(2000)
rsecs = 1000000000 - lsecs
ryears = rsecs / ysecs
puts "You are currently #{lsecdel} seconds old"
puts "You have #{ryears.round(2)} years until you are a billion seconds old!!"
答案 0 :(得分:3)
怎么样?
def reformat_date(str)
str.split('/').reverse.join(',')
end
答案 1 :(得分:1)
您可以获得任何所需格式的输入,并在下面使用此格式将其转换为yyyy,mm,dd格式
Date.parse("10/12/1995").strftime('%Y,%m,%d')
输出:1995,12,10
答案 2 :(得分:0)
require 'date'
now = Date.today
years_BACK_From_Now = (now - 365)
p years_BACK_From_Now.strftime("%m-%d-%Y").to_s
p years_BACK_From_Now.split('-').reverse.join('/')