2010-08-31 83 views
8

如何獲取Android中的當前時間?如何獲取當前時間

當我使用

int hours = java.sql.Time.this.getHours(); 

我得到的錯誤:

No enclosing instance of the type Time is accessible in scope 
+0

看到這個職位http://stackoverflow.com/questions/2271131/display-current-time-and-date-in-android-application – Ally 2010-08-31 16:35:03

回答

12
int hours = new Time(System.currentTimeMillis()).getHours(); 
+1

謝謝PERFEKT !!! – 2010-08-31 16:38:40

+1

System.currentTimeMillis()返回long並且Time沒有很長的參數!對不起,但這個代碼是錯誤的。 – mSafdel 2012-06-26 11:47:47

+0

此代碼是正確的,因爲問題是關於具有適當構造函數的java.sql.Time。 – Thorstenvv 2012-09-05 15:00:57

2

Calendar類的實例設置爲當前日期和時間。

+0

我沒有得到正確的時間 – 2010-08-31 16:37:39

4

如果你只是想在當前的時間戳,您可以使用:

long millis = System.currentTimeMillis() 

還可以獲得其它時間相關的值,如自上次啓動運行時間或總時間(包括睡眠時間)從android.os.SystemClock

10

試試這個:

int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); 

公共靜態最終詮釋HOUR_OF_DAY 自:API等級1 場數get和set表示一天中的小時。 HOUR_OF_DAY用於24小時制。例如,在10:04:15.250 PM的HOUR_OF_DAY爲22

4

我最喜歡的樣本:

Time dtNow = new Time(); 
dtNow.setToNow(); 
int hours = dtNow.hour; 
String lsNow = dtNow.format("%Y.%m.%d %H:%M"); 
String lsYMD = dtNow.toString(); // YYYYMMDDTHHMMSS 
1

Calendar cal = Calendar.getInstance(); // get current time in a Calendar

,那麼你可以做很多與日曆實例,如拿到小時紀要 - 這樣的:

int hour = cal.get(Calendar.HOUR_OF_DAY);

這時候你要定位到許多地方建議,並在MULT打印數據iple格式,或者對日期進行操作。

+0

這是目前getHours()/ getDate()等最好的答案貶值。 – Ravi 2016-06-04 06:50:07

2

給Andrew的回覆添加一點點。如果您的時區處於夏令時模式,代碼的後面部分會增加小時。 HOUR_OF_DAY採用24小時格式。

Calendar currentTime = Calendar.getInstance()    ; 
    int hour    = currentTime.get(Calendar.HOUR_OF_DAY) ; 
    int minute    = currentTime.get(Calendar.MINUTE)  ; 
    int second    = currentTime.get(Calendar.SECOND)  ; 
    long milliDiff   = currentTime.get(Calendar.ZONE_OFFSET) ; 
    // Got local offset, now loop through available timezone id(s). 
    String [] ids   = TimeZone.getAvailableIDs()   ; 
    for (String id : ids) 
      { 
     TimeZone tz = TimeZone.getTimeZone(id)     ; 
     if (tz.getRawOffset() == milliDiff) 
      { // Found a match, now check for daylight saving 
      boolean inDs = tz.inDaylightTime(new Date()) ; 
      if (inDs)  { hour += 1 ; } 
      if (hour == 25) { hour = 1 ; } 
      break            ; 
      } 
     }