Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 983
  • Last Modified:

Problems with Calendar class in J2ME.

I developing an application that runs on cellphones. I'm using the last version of the Sun Java Wirelless Toolkit (Version 2.5). I need to take the date and the hour at an specific moment so I got the following code to do this.

        calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-05:00"));
        calendar.setTime(new Date());

        // to convert the current date to an String
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        date = (month<10? "0": "")+ month+"/"+(day<10? "0": "") + day + "/" + (year<10? "0": "")+year;

        // to convert the current time to an String
        String[] AMPM = {"AM", "PM"};
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        String am_pm = (AMPM[calendar.get(Calendar.AM_PM)]);
        time = (hour + ":" + minute + am_pm);

The problem is that this piece of code works well for the Date but for the time it doesn't. It gives me one hour late that the actual one.  Another problem that I have also with the time is that when for intance is 2:07 it displays 2:7 without the zero.  If there is a way to to this in another and easy way please I will appreciate any code. Thank
  • 2
2 Solutions
Are you taking into account Daylight Savings Time?  Most people in GMT -05:00 are on Daylight Savings Time right now, which means that they have set their clocks to be one hour ahead of what would seem like the actual hour to someone not on Daylight Savings TIme.
As for the 2:7 problem, by the code you posted it seems you simply forgot to check if the minute was less than 10 and if so put out an extra zero (like you did for the date).
time = (hour + ":" + (minute<10?"0":"") + minute + am_pm)
just take out the timezone and your time would be correct

calendar = Calendar.getInstance();

As for the 2:7 problem, i think DefreeComan code is the shortest way to do it.


import java.text.DateFormat;

Date d = new Date();
DateFormat df1 = DateFormat.getDateInstance(DateFormat.DATE_FIELD);
DateFormat df2 = DateFormat.getTimeInstance(DateFormat.SHORT);
String s1 = df1.format(d);
String s2 = df2.format(d);
System.out.println("Date in dd/MM/yy format > " + s1);
System.out.println("Time in hh:mm format > " + s2);

I found this  shorter way, but the date format is fixed to dd/MM/yy, can't get you the yyyy format.

:) Hope this help

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now