Java - Working with Date/Time in J2ME

datetime, java-me

Solution

I use the following code to get time:

String getDateString(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);

    return new String(/*Any format you need*/);
}

You get numbers and then you can output them in any necessary format.

The code to create Date object is something like this:

Date createDate(String dateString) {
    //Extract needed numbers first
    StringBuffer strBuf = new StringBuffer(dateString);

    char[] charBuf = new char[4];

    strBuf.getChars(0, 3, charBuf, 0);
    dayOfWeek = new String(charBuf, 0, 3);

    strBuf.getChars(strBuf.length() - 4, strBuf.length(), charBuf, 0);
    year = charsToInt(charBuf, 4);

    strBuf.getChars(4, 7, charBuf, 0);
    String monthStr = new String(charBuf, 0, 3);
    month = ArraySearcher.searchStringEntry(monthStr, MONTHS);

    day = extractShortField(strBuf, 8, charBuf);
    hour = extractShortField(strBuf, 11, charBuf);
    minute = extractShortField(strBuf, 14, charBuf);
    second = extractShortField(strBuf, 17, charBuf);

    //Now set the calendar
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);
    calendar.set(Calendar.SECOND, second);

    return calendar.getTime();
}

private int charsToInt(char[] buf, int len) {
    String str = new String(buf, 0, len);
    return Integer.parseInt(str);
}

private int extractShortField(StringBuffer strBuf, int start, char[] charBuf) {
    strBuf.getChars(start, start + 2, charBuf, 0);
    return charsToInt(charBuf, 2);
}

That'll do the trick.

Problem

How to extract time portion from a Date-object and use it as a String in J2ME? How to convert that time-string back to Date - object in J2ME? I have done something to achieve this, but it is not showing correct-time.

Original source