2012-07-15 54 views
1

我使用Java代码来获得当前日期和时间:Java的当前时间提前我的系统的时间为2小时

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

请帮我解决这个问题!

+1

我会建议你使用[乔达时间](http://joda-time.sourceforge.net/),该库已经解决了大部分Java API所具有的Date,Time和DateTime问题。 – 2012-07-15 16:55:59

+0

将时区添加到您的formaytter – 2012-07-15 17:00:06

+0

@LuiggiMendoza您能告诉我如何使用Joda时间库分别打印当前日期和时间?谢谢 – Azeem 2012-07-15 17:11:29

回答

1

试试这个:

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)

+0

它给出相同的输出。即使我使用'日历c = Calendar.getInstance(TimeZone.getTimeZone(“UTC + 05:00”))设置我自己的时区;''但没有成功!有什么想法吗? – Azeem 2012-07-15 17:07:03

-2

你的问题是时区

为exp。

此代码为Android。

更改app的时区。

由于Android默认的时区是“UTC”

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));