Converting a calendar object to a string in java with the format "yyyy-mm-dd hh: mm: ss"

I am converting a date stored in a calendar object into a string for a query in MySQL. I need a line in the format "yyyy-MM-dd HH: mm: ss", i.e.: "2010-01-01 15:30:00". I use 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 line, and not "2010-01-01 15:30:00" as I expect, it is "2010-02-01 01:30 p.m." I 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, MM capital for a month or HH capital for several hours ), but it did not work.

I guess there is another field that I have to set, or maybe there is another method ... any idea?

+7
java datetime
source share
2 answers

Calendar.JANUARY is actually 0 , not 1 .

When you provide 01 for the month field in set , you actually set the month in February, so you get 02 when SimpleDateFormat displays it as MM .

When using any of the Calendar.get/set methods, you must take extra precautions to make sure that you are aware of this discrepancy between the "natural" indexing based on 1 and the more "inconvenient" Calendar 0- based indexing. Each time you get / set the month of Calendar , there is always such an opportunity to cause a serious error.

This is just one of those inconvenient designs in Calendar that leaves much to be desired. One of the better, more enjoyable date / time API libraries available there is Joda Time , so if at all possible, you might consider switching to that library.

API Links

  • Calendar.MONTH - "The field number for get and set , denoting the month. This is a calendar dependent value. The first month of the year [...] is JANUARY , which is 0".
  • Calendar.set(โ€ฆ, int month, โ€ฆ) - " month - the value used to set the calendar field for the month . The value of the month is 0, for example, 0 for January."

In octal literals

Also note that 01 is actually an octal literal (i.e. base 8 ). You should not be used to adding 0 to integer literals ( ยง3.10.1 ), as they can cause subtle errors / errors if you are not very careful.

For example, int i = 09; is illegal Java code.

  System.out.println(010); // prints 8, not 10 

see also

  • Can I customize syntax highlighting in Eclipse to show octal literals differently?
  • Octal number of literals: when? What for? Ever?
+8
source share

This is just a month starts at 0 (not 1 )

However, you do not have to convert to a string to insert a date in the database. You can either use a timestamp or java.sql.Date along with PreparedStatement

+3
source share

All Articles