Date Issue in J2ME

66 views Asked by At

Straight to the point with this one. Let's say the date today is 16-06-2015 and the device date matches this. I'm trying to read it in this format, 16062015. However, the date is being shown to be one month behind i.e. 16052015. My code:

public String getDate() {
    Calendar cal = Calendar.getInstance();
    int day = cal.get(Calendar.DAY_OF_MONTH);
    int month = cal.get(Calendar.MONTH);
    int year = cal.get(Calendar.YEAR);
    String dayString = String.valueOf(day);
    String monthString = String.valueOf(month);
    String yearString = String.valueOf(year);
    String date = dayString + "0" + monthString + yearString;
    return date;
}

What could be the issue?

This is in J2ME. Device: Nokia 206.

2

There are 2 answers

0
Jan On BEST ANSWER
int month = cal.get(Calendar.MONTH);

returns 0 for January, 1 for February, ... That's why your code behaves the way it does. So an easy fix would be:

int month = cal.get(Calendar.MONTH) + 1;

By the way: In October, November and December you will get an additional problem. (Hint: They have 2 digits.)

0
Philip Couling On

The as shown as an ISO date uses Jan as 1. According to the documentation the month field is base 0 and thus Jan is 0.

http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#set%28int,%20int,%20int%29