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());

7 Comments:

Blogger Tomas Szabo said...

Thank you! You saved my hair... :)

1:30 am  
Blogger dev said...

thanks...

9:04 am  
Anonymous Anonymous said...

Thanks for the info.
We can also set hour,minute and second in case we need to set the default time for a datefield element.

it works well on many devices but for nokia 5880 it does'nt sets the value in case the hour,minute and time is set.

11:55 am  
Blogger shazsterblog.blogspot.com said...

Thank you very much!

1:17 pm  
Blogger Nyambura Muhia said...

Hey,thanks very much.it has taken me days to retrieve date from the rms and you have made this absolutely possible with your code.

Thanks very much ;-)

9:15 pm  
Anonymous Chandima said...

Many Thanks.. Saved my day..
Little correction in the last line though.. it should be
df.setDate(currentTime.getTime());

7:29 am  
Blogger Diana CerĂ³n said...

Thanks a lot!!! just what I needed.
Muchas, muchas gracias!!! Justo lo que necesitaba.

:)

7:21 am  

Post a Comment

<< Home