I’m converting a date stored in a calendar object in a string for a query in MySQL. I need the string in format “yyyy-MM-dd HH:mm:ss”, i.e.: “2010-01-01 15:30:00”.
I’m using a code like:
Calendar TimeStop = Calendar.getInstance();
TimeStop.set(2010, 01, 01, 15, 30, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String TimeStop_Str = sdf.format(TimeStop.getTime());
now, the string, instead of being “2010-01-01 15:30:00″ like I would expect is “2010-02-01 15:30:00″.
I have already checked on http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html for possible errors in the parser formula (for example the capital MM for month or capital HH for hours) but it didn’t worked.
I guess that there is some other field that I should set, or maybe there is another method… any idea?
Calendar.JANUARYis actually0, not1.When you provide
01for the month field inset, you’re actually setting the month to February, which is why you get02whenSimpleDateFormatrenders it asMM.When you use any of the
Calendar.get/setmethods, you must take extra precautions to make sure that you are aware of this discrepancy between the “natural” 1-based indexing, and the more “awkward”Calendar‘s 0-based indexing. Any time you’re getting/setting the month of aCalendar, there’s always this potential to cause a serious bug.This is just one of those really awkward design in
Calendarthat leaves a lot to be desired. One of the better, more pleasant date/time API library available out there is Joda Time, so if at all possible, you may consider a switch to that library instead.API links
Calendar.MONTH– “Field number forgetandsetindicating the month. This is a calendar-specific value. The first month of the year […] isJANUARYwhich is 0″.Calendar.set(…, int month, …)– “month– the value used to set theMONTHcalendar field. Month value is 0-based. e.g., 0 for January.”On octal literals
Also, note that
01is actually an octal literal (i.e. base 8). You shouldn’t make a habit of prepending0to integer literals (§3.10.1), because they can cause subtle bugs/errors unless you’re very careful.For example,
int i = 09;is an illegal Java code.See also