Wednesday, June 07, 2006

Making Movies

The other week-end Dév and I made an animated movie of his current favourite toys, including soundtrack. He loved it - almost as much as "real" Thomas the Engine episodes.

PS: Thanks Google Video for hosting; neat! I wonder if the link above will still work in a few years?

Simple HTTP Server in Java

Just for fun (well, almost), I wrote my very own simple HTTP server in Java (download 100 KB ZIP) the other night. It uses Java5 features, and requires no external libraries. While it certainly does work and can serve a static website HTML+image site, it is of course NOT meant as a "real" web server, so do NOT use it - it's instructional, and it sure was fun to code!

PS: Almost eight years ago, I put online a Proxy Server written in C on my website, and to my big surprise, during all the years since, every now and then a CS student (presumably asked to write one for class, just like I had at the time), emails some questions... So just in case folks, if you found this page because you are looking for a cheap way out for your homework, by all means download and look at it - but then fix/improve it, and quoting the source and explaining your enhancements! And put a quick comment to this post below.

Number of days between two dates? (Java)

Recently a needed to get the number of days between two dates in Java.

Easy, right? Quite a few pages & articles suggest, and I admit my first iteration too, was:

Calendar firstDay = new GregorianCalendar(2006, Calendar.FEBRUARY, 3)
Calendar lastDay = new GregorianCalendar(2006, Calendar.JULY, 17);

static final long DAY_MS = 1000 * 60 * 60 * 24;
int days = (lastDay.getTime().getTime() - firstDay.getTime().getTime()) / DAY_MS;

It turns out this is WRONG, for example for the two dates given (days == 163, but shold be 164!) - some rounding error. This will round correctly, as some better Web pages explain:

double daysDouble = lastLong - firstLong;
int days = (int) Math.round(daysDouble / DAY_MS); // = 164

but using the Calendar API provides a clearer, more reable and most importantly correct version, too:

assert firstDay.get(Calendar.YEAR) == lastDay.get(Calendar.YEAR); // Assumption
int days = lastDay.get(Calendar.DAY_OF_YEAR) - firstDay.get(Calendar.DAY_OF_YEAR);

Or, for more calculations of this kind, consider http://joda-time.sourceforge.net/