Label Cloud

Saturday, May 31, 2008

1st Java annoyance

For the last month I've spent as much time writing Java code as C# code. And its definitely been a great learning experiences. Even though the core languages are very much alike, and you can usually find a function in .NET that corresponds to Java and the other way around, I've spent quite a bit of time yesterday trying something that should have been completely trivial.

The Problem:

having a Date variable loadDate that includes Date and Time, create two variables startDate and endDate where StartDate is the portion of the loadDate, and endDate is the startDate + 1 day

C# Code:

DateTime loadDate = DateTime.Now; DateTime startDate = loadDate.Date; DateTime endDate = startDate.AddDays(1);

Java Code#

GregorianCalendar cal = new GregorianCalendar( loadDate.getYear() + 1900, loadDate.getMonth(), loadDate.getDate()); Date startDate = cal.getTime(); cal.add(Calendar.DATE, 1); Date endDate = cal.getTime();

Why is the Date.getYear() function returning 108 for a year 2008? What is the logic behind that? Are the Java developers afraid of running out of integer values?

Why the Calendar class supplies the clearDate() function, but no clearTime() function?

Why I can't dd Dates the way I can other classes?

Why the Calendar.add() function doesn't return a result instead of replacing the internal value, the way other classes do?

Why is this not documented in the Date class?


1 comment:

Anonymous said...

Another way to do it:

Calendar loadDate = Calendar.getInstance();
Date startDate = loadDate.getTime();
loadDate.add(Calendar.DATE, 1);
Date endDate = loadDate.getTime();

As the getters/setters from the Date class are deprecated.