Monday, January 12, 2009

Setting the current time in a J2ME DateField with mode TIME

So many wasted hours! arg!

If you wanted to create a DateField with only time input (i.e. ask the user to input the time only, not a date as well), with the default value the current system time, all the documentation would point to doing it like this:


DateField df = new DateField ("Enter time:", DateField.TIME);
df.setDate(new Date());


That doesn't work, though. To set the current time in a date field, you need to pass in a date with the year, month and day values of the epoch, and the time that you want to set into the field. Like this:


Calendar epoch = Calendar.getInstance();
epoch.setTime(new Date(0));

Calendar currentTime = Calendar.getInstance();
currentTime.setTime(new Date());
currentTime.set(Calendar.YEAR,epoch.get(Calendar.YEAR));
currentTime.set(Calendar.MONTH,epoch.get(Calendar.MONTH));
currentTime.set(Calendar.DATE,epoch.get(Calendar.DATE));

DateField df = new DateField ("Enter time:", DateField.TIME);
df.setDate(new Date());