2013-07-31 3 views
1

я использовать эти коды, чтобы получить мое местное время:проблема с местным временем

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
Calendar currenDdate = Calendar.getInstance(TimeZone.getDefault()); 
System.out.print("Last update: "+dateFormat.format(currenDdate.getTime())); 

или:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
Calendar currenDdate = Calendar.getInstance(getTimeZone("GMT+3.5")); 
System.out.print("Last update: "+dateFormat.format(currenDdate.getTime())); 

, но не из них дают местное время, они оба дают мне GMT ​​ , что это проблема?

ПРИМЕЧАНИЕ: Я использую программирование eclipse и android, коды выше правильно работают в java, но в android это не так!

вместо System.out.print() я использую TextView, чтобы показать время

TextView date = (TextView) findViewById(R.id.gold_textView1); 
date.setText("Last update: "+dateFormat.format(currenDdate.getTime())); 

пожалуйста, помогите мне найти проблему

ответ

0

Попробуйте Date currentDate = new Date() вместо Calendar объекта. Ваш звонок System.out.print() не изменится. Кроме того, дважды проверьте свою систему, чтобы убедиться, что ее часовой пояс по умолчанию установлен правильно.

0

Вы пробовали, как это:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
dateFormat.setTimeZone(TimeZone.getDefault()); 
Calendar currenDdate = Calendar.getInstance(TimeZone.getDefault()); 
System.out 
    .print("Last update: " + dateFormat.format(currenDdate.getTime())); 
0

Вместо Calendar вам необходимо установить ваш TimeZone на SimpleDateFormat:

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z"); 
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+0330")); 

// prints: Last update: 2013/07/31 18:46:24 +0330 
System.out.println("Last update: " + dateFormat2.format(currenDdate.getTime())); 

Это необходимо потому, что SimpleDateFormat использует Calendar экземпляр своего собственного внутренне.

См SimpleDateFormat#setTimeZone()

public void setTimeZone(TimeZone zone) 
{ 
    calendar.setTimeZone(zone); 
} 

Обратите внимание, шаблон формат даты также включает в себя зону письма времени Z включить его на дисплее.

0

Попробуйте использовать JodaTime http://www.joda.org/joda-time/

DateTimeZone dateTimeZoneUTC = DateTimeZone.UTC; 
DateTime dateTimeUTC = new DateTime().withZone(dateTimeZoneUTC); 

DateTimeZone dateTimeZoneLocal = DateTimeZone.getDefault(); 
DateTime dateTimeLocal = dateTimeUTC.withZone(dateTimeZoneLocal); 

DateTimeZone dateTimeZoneOffset = DateTimeZone.forID("-03:00"); 
DateTime dateTimeOffset = dateTimeLocal.withZone(dateTimeZoneOffset); 

// Airport Current Time hh/mm 
DateTimeFormatter timeFormat = DateTimeFormat.forPattern("hh/mm").withZone(dateTimeZoneOffset); 
currentTime.setText(timeFormat.print(dateTimeOffset)); 
Смежные вопросы