2013-08-24 49 views
3

我有一個函數會輸出yyyy/mm/dd hh:mm:ss。除了小時之外,一切都非常準確,似乎是6小時。任何想法爲什麼?使用currentTimeMillis並關閉6個小時

public static void dateAndTime() { 
    Calendar cal = Calendar.getInstance(); 
    int month = cal.get(Calendar.MONTH)+1; 
    int day = cal.get(Calendar.DATE); 
    int year = cal.get(Calendar.YEAR); 

    long totalMilliseconds = System.currentTimeMillis(); 
    long totalSeconds = totalMilliseconds/1000; 
    int currentSecond = (int)(totalSeconds % 60); 
    long totalMinutes = totalSeconds/60; 
    int currentMinute = (int)(totalMinutes % 60); 
    long totalHours = totalMinutes/60; 
    int currentHour = (int)(totalHours % 24); 
     System.out.println (year + "-" + month + "-" + day + " " + currentHour + ":" + currentMinute + ":" + currentSecond); 
} 

回答

1

這是一個與時區相關的問題。所述Calendar類默認爲當地時區,而該方法System.currentTimeMillis的()(如在Javadoc指定)返回:

的差,以毫秒爲單位,當前時間和午夜之間,1970年1月1日世界標準時間。

2

currentTimeMillis()給你,因爲在固定時間點叫the Unix epoch以來經過的毫秒數:00:00:00 UTC在1970年1月

這裏得到正確的時間的一種方式:

import java.util.Calendar; 
import java.util.TimeZone; 
import java.util.Date; 
import java.text.DateFormat; 
import java.text.SimpleDateFormat; 

class Clock { 
    public static void main(String[] args) { 
     DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     df.setTimeZone(TimeZone.getTimeZone("Europe/Athens")); 
     Date currentDate = new Date(); 
     System.out.println(df.format(currentDate)); 
    } 
} 

輸出(雅典當地時間):

2013-08-24 23:54:45