Bert's Blog

Apr 3

Despicable Dates

A long time ago, I had the unpleasant task of writing a library for “intuitively” parsing Dates. As with most mental trauma, I cannot recall what happened, but I still fly into a blind rage when I see one written m/d/y.

The other day I came across this neat piece of code for calculating a countdown broken down into days, hours, minutes and seconds:

public void Countdown(long lo, long hi) {
  int diff = (int) (hi - lo)/1000;
  days = diff/(24*60*60);
  hours = diff/(60*60) - days*24;
  mins = diff/60 - days*24*60 - hours*60;
  secs = diff - days*24*60*60 - hours*60*60 - mins*60;

Of course these is absolutely nothing wrong with this code … if you happen live in a sane country. Unfortunately I live in England and we do things slightly differently. Yes I’m referring to “British Summer Time” which decides that one day a year will have 23 hours, and another 25! This means we have to do stupid things like this:

public Countdown(Calendar lo, Calendar hi) {
  int loOffset = lo.getTimeZone()
  int hiOffset = hi.getTimeZone()
  int offset = loOffset - hiOffset;

  Calendar temp = (Calendar)hi.clone();
  temp.add(MILLISECOND, offset);
  secs = temp.get(SECOND) - lo.get(SECOND);
  mins = temp.get(MINUTE) - lo.get(MINUTE);
  hours = temp.get(HOUR_OF_DAY) - lo.get(HOUR_OF_DAY);
  days = temp.get(DAY_OF_YEAR) - lo.get(DAY_OF_YEAR);		

  if(secs < 0) {
    secs += temp.getActualMaximum(SECOND)+1;
  if(mins < 0) {
    mins += temp.getActualMaximum(MINUTE)+1;
  if(hours < 0) {
    hours += temp.getActualMaximum(HOUR_OF_DAY)+1;

Perhaps I should move to a country where daylight isn’t in such short supply!

  1. berthamilton posted this