Ruby converts string DD / MM / YYYY to YYYY, MM, DD

I am collecting user input as "DD / MM / YYYY"

The goal is to go to mktime like csv YYYY, MM, DD.

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!!"

      

As you can see, the only remaining task is to undo the user input without having any trouble finding a compact solution. Feel free to make this code shorter if you see a way.

Solution: (with old seconds and years rounded / capped)

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!!"

      

+3


source to share


2 answers


What about?



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

      

+2


source


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('/')

      



0


source







All Articles