gpt4 book ai didi

date - Ruby 将 DD/MM/YYYY 字符串转换为 YYYY,MM,DD

转载 作者:行者123 更新时间:2023-12-02 16:17:22 25 4
gpt4 key购买 nike

我正在收集用户输入的“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!!"

最佳答案

什么?

def reformat_date(str)
str.split('/').reverse.join(',')
end

关于date - Ruby 将 DD/MM/YYYY 字符串转换为 YYYY,MM,DD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31772343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com