How to get current hour in android?

Time class is no longer possible to use. I want to ask you, how to detect in app 3-4am? I need that to set up for example night mode in my app.

Can you give me some example how to do it?


Instead of using Time (because Time class was deprecated in API level 22.) you can use Calendar for getting current hour

val rightNow = Calendar.getInstance()
val currentHourIn24Format: Int =rightNow.get(Calendar.HOUR_OF_DAY) // return the hour in 24 hrs format (ranging from 0-23)
val currentHourIn12Format: Int = rightNow.get(Calendar.HOUR) // return the hour in 12 hrs format (ranging from 0-11)

We can use the Calendar class to get a format like "HH:mm:ss"

Calendar calendar = Calendar.getInstance();
int hour24hrs = calendar.get(Calendar.HOUR_OF_DAY); 
int hour12hrs = calendar.get(Calendar.HOUR); 
int minutes = calendar.get(Calendar.MINUTE); 
int seconds = calendar.get(Calendar.SECOND); 
System.out.println("Current hour 24hrs format:  " + hour24hrs + ":" + minutes +":"+ seconds);
System.out.println("Current hour 12hrs format:  " + hour12hrs + ":" + minutes +":"+ seconds);

Other option using the Date class and applying the format "HH:mm:ss":

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String dateformatted = dateFormat.format(date);
System.out.println(dateformatted);

You can use following methods:

SimpleDateFormat format = new SimpleDateFormat("HH", Locale.US);
String hour = format.format(new Date());

Calendar calendar = Calendar.getInstance();
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);