How to get the current time in Android?
When i use
int hours = java.sql.Time.this.getHours();
i get the error:
No
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
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.
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.
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 ;
}
}