How to set DateField value using a string containing the date and time?
I have the following string "29/05/2012 12:11 PM" i want to add this value to a DateField
i did it like this:
String dateTime = "29/05/2012 12:11 PM";
long initialDateTime = System.currentTimeMillis();
SimpleDateFormat SDF_DateTime = new SimpleDateFormat("dd/MM/yyyy hh:mm aa");
DateField DF_DateTime = new DateField("Time: ", init开发者_开发问答ialDateTime , SDF_DateTime, Field.FIELD_LEFT | DrawStyle.LEFT | Field.FOCUSABLE);
DF_DateTime.setTimeZone(TimeZone.getDefault());
DF_DateTime.setDate(stringToDate(dateTime));
add(DF_DateTime);
where
public Date stringToDate(String s)
{
Calendar c = Calendar.getInstance(TimeZone.getDefault());
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(s.substring(0, 2)));
c.set(Calendar.MONTH, Integer.parseInt(s.substring(3, 5)) - 1);
c.set(Calendar.YEAR, Integer.parseInt(s.substring(6, 10)));
c.set(Calendar.HOUR, Integer.parseInt(s.substring(11, 13)));
c.set(Calendar.MINUTE, Integer.parseInt(s.substring(14, 16)));
c.set(Calendar.SECOND, 0);
c.set(Calendar.AM_PM, s.substring(17, 19).toLowerCase().equals("am") ? Calendar.AM : Calendar.PM);
return c.getTime();
}
But the field shows: "30/05/2012 12:11 AM"
instead of "29/05/2012 12:11 PM"
If it's usefull to know, my device is set in options to the following timezone: "Dublin, London (GMT)"
Is there any logical interpretation of what is happening ?
I've found the solution, here it is for those who are interested:
c.set(Calendar.HOUR, Integer.parseInt(s.substring(11, 13)) % 12);
Because in the javadoc for Calendar.HOUR
it's specified that:
HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12
精彩评论