[英]Java Current Time is 2 hours ahead of my system's Time
我正在使用以下Java代碼獲取當前日期和時間:
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println(timeFormat.format(date));
輸出時間總是比我的系統時間或時區早2小時。 例如,如果上面的代碼輸出以下時間:
11:44:43
那么我的系統時間是:
09:44:43
請幫我解決這個問題!
嘗試這個:
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
TimeZone tz = TimeZone.getDefault();
Calendar c = Calendar.getInstance(tz);
Date date = c.getTime();
System.out.println(timeFormat.format(date));
如果不起作用,請嘗試更改時區。 看一下TimeZone.getTimeZone(String id)
。
你的問題是時區
對於exp。
此代碼適用於android。
更改應用程序的時區。
因為android默認時區為“ UTC”
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.