SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2004
    Location
    Ann ARbor
    Posts
    14
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Subtracting Two Dates

    I am trying to subtract on date from the other to find how many days have passed.

    I want to know what I need to do to determine

    date_sent = 2007-01-01
    date_now = Date.today

    I want to be able to subtract the date_sent from date_now and return the accurate number of days that have passed. Does anyone know how to do this? I also what to make sure it actually accounts for months being an uneven number of days.

    Thanks
    JP

  2. #2
    SitePoint Zealot daveporter's Avatar
    Join Date
    Mar 2002
    Location
    Perth, Western Australia
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi JP,

    I'm learning Ruby and need to understand dates a lot so your questions was of interest to me...

    Here is a little program I played around with to experiment. I hope it helps.

    The fourth 'puts' displays the number of days between today and the first date of the current year !

    Dave Porter
    p.s. of course I'm sure a function could be written to work out the first date of the current year, but I have simply explicitly placed it in a variable !

    require "date"
    date_now = Date.today
    date_yesterday = Date.today-1
    first_day_of_year = Date.new(2007, 1, 1)
    puts date_now
    puts date_yesterday
    puts first_day_of_year
    puts date_now - first_day_of_year

  3. #3
    SitePoint Evangelist
    Join Date
    Feb 2006
    Location
    Worcs. UK
    Posts
    404
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Calculating the difference between dates isn't to difficult as daveporter has shown. Months are a little more fun. My tips would be:
    • Make sure you compare like with like. There are three Ruby classes that can be used for dates: Date, DateTime, and Time. You need to convert/create the current date and your target date to/in the same class if you want to compare them to get the difference.
    • There are some Rails methods for counting months (see the Rails API pages). Be careful using these because the code behind is basic. Early versions used a definition of a month as 30 days.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •