Ray's Community

Please login or register.

Login with username, password and session length
Advanced search  

News:

Boss is working on the security

Author Topic: newb steps - birthday.rb  (Read 27 times)

rdl-admin

  • Administrator
  • Newbie
  • *****
  • Karma: +3000/-0
  • Posts: 9
  • The Administrator
    • View Profile
newb steps - birthday.rb
« on: October 15, 2018, 07:10:26 PM »

After a few hours stumbling through ancient tutorials and dated support notes, I went from 20 easy minutes(https://www.ruby-lang.org/en/documentation/quickstart/) through a few hours debugging to a working script -

Code: [Select]
# http://www.techotopia.com/index.php/Working_with_Dates_and_Times_in_Ruby#Calculating_the_Difference_Between_Dates
require 'date'

# https://stackoverflow.com/questions/46717906/what-is-the-modern-equivalent-of-ruby-s-deprecated-date-day-fraction-to-time
class Date
  def self.day_fraction_to_time(fr)
fr *= 86_400
    ss,  fr = fr.divmod(1)
    h,   ss = ss.divmod(3600)
    min, s  = ss.divmod(60)
d, h  = h.divmod(24)
    return d, h, min, s, fr
  end
end

today = DateTime.now
puts "Today: " + today.to_s

timezone = today.to_s[19, 6]
birthdate = DateTime.new(1986, 12, 11, 0, 0, 0, timezone)
puts "Date of Birth: " + birthdate.to_s

birthday = DateTime.new(today.year, birthdate.month, birthdate.day, 0, 0, 0, timezone)

if birthday < today then birthday = DateTime.new(birthday.year + 1, birthday.month, birthday.day, 0, 0, 0, timezone) end

time_until = birthday - today
time_until.to_i             # get the number of days until my birthday
days,hours,minutes,seconds,frac = Date.day_fraction_to_time(time_until)
seconds += frac.fdiv(1)

puts "It is my birthday in #{days} days, #{hours} hours, #{minutes} minutes and #{seconds} seconds (not that I am counting)"

Generating this output -
Code: [Select]
Today: 2018-10-15T19:09:48+07:00
Date of Birth: 1986-12-11T00:00:00+07:00
It is my birthday in 56 days, 4 hours, 50 minutes and 11.446173 seconds (not that I am counting)

Moving on . . .
« Last Edit: October 15, 2018, 07:12:52 PM by rdl-admin »
Logged