5

I'm collecting a users input as "DD/MM/YYYY"

The aim is to pass into mktime as 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 task remaining is to reverse the users input, having trouble finding a compact solution. Feel free to help make this code shorter if you see a way.

Solution: (with seconds old and years rounded down/delimited)

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!!"
Barris
  • 969
  • 13
  • 29

3 Answers3

4

What about?

def reformat_date(str)
  str.split('/').reverse.join(',')
end
tompave
  • 11,952
  • 7
  • 37
  • 63
2

you can get input in any desired format and use this below to convert into yyyy,mm,dd format

Date.parse("10/12/1995").strftime('%Y,%m,%d')

output : 1995,12,10

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('/')
Ohjeah
  • 1,269
  • 18
  • 24