开发者

How to get the current Time

How to get the current time in Android?

When i use

int hours = java.sql.Time.开发者_如何转开发this.getHours();

i get the error:

No enclosing instance of the type Time is accessible in scope


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


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.


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


If you just want the current timestamp, you can use:

long millis = System.currentTimeMillis()

You can also get other time related values such as the uptime or total elapsed time since the last boot (including sleep time) from android.os.SystemClock.


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜