tags:

views:

14

answers:

1

We can't use java.text.SimpleDateFormat, so is there any way to create date object from year,month,day in Java ME?

+1  A: 

I found solution, Here is the code:

    public static Date parseDate(String dateString) throws IllegalArgumentException {
Date date = new Date(0);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

System.out.println("Calendar Before "+date);

if (dateString == null || dateString.equals("")) {
throw new IllegalArgumentException("Invalid String to Parse as Date - dateString was null or empty");
}

int strSize = dateString.length();

if (strSize < 21) {
throw new IllegalArgumentException("Invalid String to Parse as Date - dateString invalid string length ("+strSize+")");
}

String yearStr = dateString.substring(0,4);
String monthStr = dateString.substring(5,7);
String dayStr = dateString.substring(8,10);
String hourStr = dateString.substring(11,13);
String minuteStr = dateString.substring(14,16);
String secondsStr = dateString.substring(17,19);
String millisStr = dateString.substring(20,Math.min(strSize,23));

int year = 0;
int day = 0;
int month = 0;
int hour = 0;
int minute = 0;
int seconds = 0;
int millis = 0;

try {
year = Integer.parseInt(yearStr);
} catch (Exception e) {
throw new DateParseException("Could not parse '"+yearStr+"' as a valid year");
}
try {
day = Integer.parseInt(dayStr);
} catch (Exception e) {
throw new DateParseException("Could not parse '"+dayStr+"' as a valid day");
}
try {
month = Integer.parseInt(monthStr) - 1; //Zero Based Months
} catch (Exception e) {
throw new DateParseException("Could not parse '"+monthStr+"' as a valid month");
}

try {
hour = Integer.parseInt(hourStr);
} catch (Exception e) {
throw new DateParseException("Could not parse '"+hourStr+"' as a valid hour");
}
try {
minute = Integer.parseInt(minuteStr);
} catch (Exception e) {
throw new DateParseException("Could not parse '"+minuteStr+"' as a valid minute");
}
try {
seconds = Integer.parseInt(secondsStr);
} catch (Exception e) {
throw new DateParseException("Could not parse '"+secondsStr+"' as a valid seconds");
}
try {
millis = Integer.parseInt(millisStr);
} catch (Exception e) {
throw new DateParseException("Could not parse '"+millisStr+"' as a valid millis");
}

System.out.println("Y: "+year+" M: "+month+" D: "+day);
System.out.println("H: "+hour+" m: "+minute+" s: "+seconds+" S: "+millis);

cal.set(Calendar.MONTH,month);
cal.set(Calendar.DATE,day);
cal.set(Calendar.YEAR,year);
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,minute);
cal.set(Calendar.SECOND,seconds);

System.out.println("Date After "+date);
date = cal.getTime();

return date;
}
Hameds