[Haskell-beginners] iterating over a range of dates

Alexander Dunlap alexander.dunlap at gmail.com
Sat Jul 9 18:52:22 CEST 2011


On 9 July 2011 09:33, Rolf Hanson <rolf.hanson at gmail.com> wrote:
> Hi, I'm trying to iterate over a range of dates and print them out.
> Here's how I am doing it in Ruby:
>
> 'require 'date'
>
> now      = Date.parse('2011-07-11')
> end_date = Date.parse('2011-12-31')
>
> (now..end_date).each do |d|
>  # print out a date that looks like:
>  # Monday, July 11, 2011
>  puts "#{d.strftime('%A, %B %d, %Y')}"
> end
>
> I've been looking at the docs for Data.Time.Format and Data.Time.Calendar and am a bit puzzled at where to begin. Anyone have ideas? I've not found many (any?) examples of time and date manipulation in Haskell.
>
> RW
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>

A good starting point would be the Enum instance of Day in
Data.Time.Calendar, which lets you use the [a..b] syntactic sugar to
do a range. fromGregorian will get you from a year, month, and day to
the Day type:

Prelude Data.Time.Calendar> [fromGregorian 2011 07 09..fromGregorian 2011 07 20]
[2011-07-09,2011-07-10,2011-07-11,2011-07-12,2011-07-13,2011-07-14,2011-07-15,2011-07-16,2011-07-17,2011-07-18,2011-07-19,2011-07-20]

This is equivalent to

enumFromTo (fromGregorian 2011 07 09) (fromGregorian 2011 07 20)

formatTime in Data.Time.Format will probably get you the rest of the way.

Hope that helps,
Alex



More information about the Beginners mailing list