How to get the current Time

前端 未结 7 2159
陌清茗
陌清茗 2021-01-04 11:28

How to get the current time in Android?

When i use

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

i get the error:

No          


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 12:08

    Just adding a little to Andrew's reply. The later part of the code increments the hour if your time zone is in daylight savings mode. The HOUR_OF_DAY is in 24 hour format.

        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                                             ;
              }
            }
    

提交回复
热议问题