2015-04-26 2 views
1

Я пытаюсь показать разницу между двумя датами, разбитыми по месяцам, дням, часам, минутам и секундам. Код, как представляется, работает, за исключением того, что часы всегда выключены на 4. Я пробовал как HOUR, так и HOUR_OF_DAY, но получаю те же результаты.Часы отключены на 4

Calendar cal = Calendar.getInstance(); 

    int year = cal.get(Calendar.YEAR); 
    int month = cal.get(Calendar.MONTH); 
    int day = cal.get(Calendar.DAY_OF_MONTH); 
    int hour = cal.get(Calendar.HOUR); 
    int minutes = cal.get(Calendar.MINUTE); 
    int seconds = cal.get(Calendar.SECOND); 


    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 

    try { 
     //get the current date/time 
     Date beginDate = cal.getTime(); 

     //fabricate a future date/time 
     Date endDate = dateFormat.parse(String.valueOf(year) + "-" + String.valueOf(month) 
       + "-" + String.valueOf(day+95) + " " + String.valueOf(hour+2) 
       + ":" + String.valueOf(minutes +16) + ":" + String.valueOf(seconds +34)); 

     long millis = endDate.getTime() - beginDate.getTime(); 

     TextView txtMonths = (TextView) findViewById(R.id.months); 
     txtMonths.setText("Months: " + (new SimpleDateFormat("M")).format(new Date(millis))); 

     TextView txtDays = (TextView) findViewById(R.id.days); 
     txtDays.setText("Days: " + (new SimpleDateFormat("d")).format(new Date(millis))); 

     TextView txtHours = (TextView) findViewById(R.id.hours); 
     txtHours.setText("Hours: " + (new SimpleDateFormat("h")).format(new Date(millis))); 

     TextView txtMinutes = (TextView) findViewById(R.id.minutes); 
     txtMinutes.setText("Minutes: " + (new SimpleDateFormat("m")).format(new Date(millis))); 

     TextView txtSeconds = (TextView) findViewById(R.id.seconds); 
     txtSeconds.setText("Seconds: " + (new SimpleDateFormat("s")).format(new Date(millis))); 

    } catch (ParseException ex) { 
     Log.d("ParseException", ex.toString()); 

    } 

Предполагалось, что это из-за TimeZone. Я GMT +8 и DST = TRUE таким образом

TimeZone timeZone = cal.getTimeZone(); 
timeZone.getOffset(System.currentTimeMillis())); 

Возвращает 7 часов не 4. Я пропускаю что-то с TimeZone информацию?

+5

Полагаю, вы не учитываете часовые пояса. – CommonsWare

+1

Проверьте, что временные интервалы не являются проблемой. Последовательное отключение на 4 часа звучит так, как будто это может быть так. – Sami

+0

Да, часовой пояс. Благодарю. Я GMT +8. Интересно, где это происходит с 4. – user1091524

ответ

0

ЭТО НЕПРАВИЛЬНО Я думал, что у меня это было, но я этого не делаю.

Я думаю, что это был часовой пояс, но я до сих пор не знаю, как это получилось с 4, когда я нахожусь по-умолчанию GMT + 8 и в DST. Так что, хотя код, как представляется, работает, я бы чувствовал себя более комфортно, если бы он был отключен на 7 или 8. Если бы это было так, часовой пояс сразу же рассердился бы на меня.

Java может быть жестоким.

Calendar cal = Calendar.getInstance(); 
    TimeZone UTC = TimeZone.getTimeZone("UTC"); 
    cal.setTimeZone(UTC); 

    int year = cal.get(Calendar.YEAR); 
    int month = cal.get(Calendar.MONTH); 
    int day = cal.get(Calendar.DAY_OF_MONTH); 
    int hour = cal.get(Calendar.HOUR); 
    int minutes = cal.get(Calendar.MINUTE); 
    int seconds = cal.get(Calendar.SECOND); 


    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 

    try { 
     //get the current date/time 
     Date beginDate = cal.getTime(); 

     //fabricate a future date/time 

     endDate = dateFormat.parse(String.valueOf(year) + "-" + String.valueOf(month) 
       + "-" + String.valueOf(day+95) + " " + String.valueOf(hour+2) 
       + ":" + String.valueOf(minutes +1) + ":" + String.valueOf(seconds +34)); 
     dateFormat.setTimeZone(UTC); 

     long millis = endDate.getTime() - beginDate.getTime(); 

     if (TimeZone.getDefault().inDaylightTime(new Date())) { 
      millis += 3600000; 
     } 

     TextView txtMonths = (TextView) findViewById(R.id.months); 
     txtMonths.setText("Months: " + (new SimpleDateFormat("M")).format(new Date(millis))); 

     TextView txtDays = (TextView) findViewById(R.id.days); 
     txtDays.setText("Days: " + (new SimpleDateFormat("d")).format(new Date(millis))); 

     TextView txtHours = (TextView) findViewById(R.id.hours); 
     txtHours.setText("Hours: " + (new SimpleDateFormat("h")).format(new Date(millis))); 

     TextView txtMinutes = (TextView) findViewById(R.id.minutes); 
     txtMinutes.setText("Minutes: " + (new SimpleDateFormat("m")).format(new Date(millis))); 

     TextView txtSeconds = (TextView) findViewById(R.id.seconds); 
     txtSeconds.setText("Seconds: " + (new SimpleDateFormat("s")).format(new Date(millis))); 
    } catch (ParseException ex) { 
     Log.d("ParseException", ex.toString()); 

    } 
Смежные вопросы