How to get the current Time

前端 未结 7 2071
陌清茗
陌清茗 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 11:51

    My favorite sample:

    Time dtNow = new Time();
    dtNow.setToNow();
    int hours = dtNow.hour;
    String lsNow = dtNow.format("%Y.%m.%d %H:%M");
    String lsYMD = dtNow.toString();    // YYYYMMDDTHHMMSS
    
    0 讨论(0)
  • 2021-01-04 11:51

    The instance of the Calendar Class is set to the current date and time.

    0 讨论(0)
  • 2021-01-04 11:51

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

    then you can do lots with the Calendar instance, such as get the Hours or the Minutes - like:

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

    This is recommended when you have to localize to many locales, and print data in multiple formats, or do operations on dates.

    0 讨论(0)
  • 2021-01-04 11:55
    int hours = new Time(System.currentTimeMillis()).getHours();
    
    0 讨论(0)
  • 2021-01-04 12:01

    Try this:

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

    public static final int HOUR_OF_DAY Since: API Level 1 Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.

    0 讨论(0)
  • 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                                             ;
              }
            }
    
    0 讨论(0)
提交回复
热议问题