Recently, in the project, we found that the Java acquisition system time new date (). tolocalestring () is 13 hours different. This was not the case before, but only after the upgrade.
The specific cause is still learning ing!
The solution is as follows:
Java code
- ImportJava. Text. simpledateformat;
- ImportJava. util. calendar;
- ImportJava. util. date;
- ImportJava. util. locale;
- ImportJava. util. timezone;
- Public ClassDateutil {
- Public StaticString getcurrentyyyymmdd (){
- Simpledateformat formatter =NewSimpledateformat ("yyyy-mm-dd", locale. US );
- Formatter. settimezone (timezone. gettimezone ("GMT + 8 "));
- Date currtime =NewDate ();
- String thistime =NewString (formatter. Format (currtime ));
- ReturnThistime;
- }
- Public StaticString getcurrentyyyymmddhhmmss (){
- Simpledateformat formatter =NewSimpledateformat ("yyyy-mm-dd hh: mm: SS", locale. US );
- Formatter. settimezone (timezone. gettimezone ("GMT + 8 "));
- Date currtime =NewDate ();
- String thistime =NewString (formatter. Format (currtime ));
- ReturnThistime;
- }
- Public Static VoidMain (string [] ARGs ){
- System. out. println (DateUtil. getCurrentYYYYMMDD ());
- System. out. println (DateUtil. getCurrentYYYYMMDDHHMMSS ());
- System. out. println (NewDate (). toLocaleString ());
- }
- }
import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Locale;import java.util.TimeZone;public class DateUtil { public static String getCurrentYYYYMMDD(){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("GMT+8")); Date currTime = new Date(); String thisTime = new String(formatter.format(currTime)); return thisTime;} public static String getCurrentYYYYMMDDHHMMSS(){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("GMT+8")); Date currTime = new Date(); String thisTime = new String(formatter.format(currTime)); return thisTime;} public static void main(String[] args){ System.out.println(DateUtil.getCurrentYYYYMMDD());System.out.println(DateUtil.getCurrentYYYYMMDDHHMMSS());System.out.println(new Date().toLocaleString());}}
Output result:
Java code
- 2008-10-10
- 01:52:22
- 12:52:22
2008-10-102008-10-10 01:52:222008-10-9 12:52:22
From: http://qqwyy.javaeye.com/blog/251045