Convert the calendar object to a string in Java format, with the format “yyyy MM DD HH: mm: SS”

I am converting the date stored in the calendar object in the string into a query in MySQL I need a string in the format "yyyy MM DD HH: mm: SS", that is: "2010-01-01 15:30:00"

Calendar TimeStop = Calendar.getInstance();
    TimeStop.set(2010,01,15,30,0);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String TimeStop_Str = sdf.format(TimeStop.getTime());

Now, instead of "2010-01-01 15:30:00" as I expected, the string is "2010-02-01 15:30:00" I'm already here http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html Possible errors in the parser formula (for example, month's capital mm or hour's capital HH) were checked on, but it didn't work

I think I should set up some other areas, or maybe there is another way... Any idea?

Solution

Calendar. January is actually 0, not 1

When you provide 01 for the month field in the collection, you actually set the month to February, which is why you get 02 when simpledateformat renders it as mm

When you use any calendar When using the get / set method, you must take additional precautions to ensure that you understand the difference between the "natural" 1-based index and the more "clumsy" 0-based index Every time you get / set the calendar month, this can lead to serious errors

This is just one of those very clumsy designs in calendar, and there are many shortcomings One of the better and more enjoyable date / time API libraries is joda time, so you can consider switching to it if possible

API link

> Calendar. Month – "gets and sets the field number representing the month. This is a calendar specific value. The first month of the year is January, i.e. 0." > Calendar. Set (..., int month,...) – "month – used to set the value of the month calendar field. The month value is 0. For example, 0 means January."

Octal text

Also, note that 01 is actually octal text (i.e. base 8) You should not get into the habit of adding zeros to integer text (§ 3.10.1) because they can lead to subtle errors / errors unless you are very careful

For example, int i = 09; Is an illegal java code

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

You can also have a look

> Can I customize syntax highlighting in Eclipse to show octal literals differently? > Octal number literals: when? why? ever?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>