Handling Commercial Dates

Problem

When writing a business or financial application, you need to deal with commercial dates instead of civil or calendar dates.

Solution

DateTime offers some methods for working with commercial dates. Date#cwday gives the commercial day of the week, Date#cweek gives the commercial week of the year, and Date#cwyear gives the commercial year.

Consider January 1, 2006. This was the first day of calendar 2006, but since it was a Sunday, it was the last day of commercial 2005:

	require 'date'
	sunday = DateTime.new(2006, 1, 1)
	sunday.year # => 2006
	sunday.cwyear # => 2005
	sunday.cweek # => 52
	sunday.wday # => 0
	sunday.cwday # => 7

Commercial 2006 started on the first weekday in 2006:

	monday = sunday + 1
	monday.cwyear # => 2006
	monday.cweek # => 1

 

Discussion

Unless you're writing an application that needs to use commercial dates, you probably don't care about this, but it's kind of interesting (if you think dates are interesting). The commercial week starts on Monday, not Sunday, because Sunday's part of the weekend. DateTime#cwday is just like DateTime#wday, except it gives Sunday a value of seven instead of zero.

This means that DateTime#cwday has a range from one to seven instead of from zero to six:

	(sunday…sunday+7).each do |d|
	 puts "#{d.strftime("%a")} #{d.wday} #{d.cwday}"
	end
	# Sun 0 7
	# Mon 1 1
	# Tue 2 2
	# Wed 3 3
	# Thu 4 4
	# Fri 5 5
	# Sat 6 6

The cweek and cwyear methods have to do with the commercial year, which starts on the first Monday of a year. Any days before the first Monday are considered part of the previous commercial year. The example given in the Solution demonstrates this: January 1, 2006 was a Sunday, so by the commercial reckoning it was part of the last week of 2005.

See Also

  • See Recipe 3.3, "Printing a Date," for the strftime directives used to print parts of commercial dates


Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net