Original URL: http://highforest.blog.51cto.com/125539/842496/
People familiar with Oracle database should know: Select To_char (sysdate, ' Yyyy-mm-dd ' Hh24:mi:ss) from dual will find out what kind of results, good, is similar to 2012-04-23 20:43:57 such a 19-bit string. So how do you get such a string in Java? A number of similar examples have been given online, but have been tried. Had to carefully study the Java API documentation, finally found a solution:
- Import java.util.*;
- Import java.text.*;
- public class Testcalendar {
- /**
- * @param args
- */
- public static void Main (string[] args) {
- Calendar cal1 = calendar.getinstance ();
- Timezone.setdefault (Timezone.gettimezone ("gmt+8:00")); Very critical!!!
- Java.text.SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd kk:mm:ss");
- System.out.println (Sdf.format (Cal1.gettime ()));
- }
- }
What needs to be explained is this one timezone.setdefault (Timezone.gettimezone ("gmt+8:00")); Very critical, without this sentence, the result must be GMT standard time, not Beijing times!
It is also necessary to note that each time the current moment is read by calling Calendar.getinstance () and not deceived by the Calendar.gettime () method:
- public class Testcalendar {
- /**
- * @param args
- */
- public static void Main (string[] args) {
- Calendar cal1 = calendar.getinstance ();
- Timezone.setdefault (Timezone.gettimezone ("gmt+8:00"));
- Java.text.SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd kk:mm:ss SSS");
- System.out.println (Sdf.format (Cal1.gettime ()));
- for (int i = 0; I<; i++) {
- float f = 999999.9f;
- do {
- ff = f-1.0000001f;
- } while (f>0.0f);
- }
- Cal1 = calendar.getinstance ();
- System.out.println (Sdf.format (Cal1.gettime ()));
- }
- }
Will output two identical time strings:
2012-04-23 21:11:56 699
2012-04-23 21:11:56 699
After removing the comment from line 17th, the output is:
2012-04-23 21:13:28 736
2012-04-23 21:13:29 235
"Go" method of obtaining local time in Java--good