Hi there,
Im reading a date out of a database and I need to subtract exactly 1
month from that date? It needs to be bullet proof so that if the date
says 31 and the previous month only has 28 days it wont just subtract 1
from the month and make an illegal date.
Hi there,
Im reading a date out of a database and I need to subtract exactly 1
month from that date? It needs to be bullet proof so that if the date
says 31 and the previous month only has 28 days it wont just subtract 1
from the month and make an illegal date.
days_ago and weeks_ago aren’t there because they are easy: days_ago is
just n * 86400 seconds ago, so you can just write 3.days.ago
months_ago is more complicated because of the varying numbers of day in
a month, you need to now what the value of now is, which is why we have
months_ago, months_since
A word of warning about Date, Date can be quite slow compared to Time.
Most of the time you won’t care, but I was writing a calendaring style
app that did a lot of that sort of calculations and using profiling
showed that the various Date operations were a big slowdown
days_ago and weeks_ago aren’t there because they are easy: days_ago is
just n * 86400 seconds ago, so you can just write 3.days.ago
months_ago is more complicated because of the varying numbers of day in
a month, you need to now what the value of now is, which is why we have
months_ago, months_since
A word of warning about Date, Date can be quite slow compared to Time.
Most of the time you won’t care, but I was writing a calendaring style
app that did a lot of that sort of calculations and using profiling
showed that the various Date operations were a big slowdown
Fred
Can someone elaborate on the Date Vs Time speed comment?
I am about to write a lot of calendar like functionality that doesn’t
really need hour/minute level details and was thinking using Date
throughout. But if it means taking a performance hit, I will reconsider.
Simply put, Time values are stored as a long integer and all math on
them is done by adding or subtracting two values. This is very fast.
Date does a bunch of processing to make sure things work fine, which is
slower.
BTW…
irb>require ‘rubygems’
irb>require ‘ruby-units’ (gem for unit conversions and unit math)
irb>require ‘chronic’ (interprets natural language time specs)
irb>‘2 weeks’.from ‘today’
#=> Mon Nov 06 17:00:00 EST 2006
irb>‘2 weeks’.from ‘today’.to_date
=> 2006-11-06
also does… ‘ago’, ‘from’, ‘until’, etc…
but ruby-units doesn’t do months since they aren’t a fixed size
interval.
It does contain a number of helpers for converting back and forth
between time and date objects, and it will automatically convert to a
date object if any math you do takes you outside the normal range for a
Time object.