I am trying to get current time as e.g. 09:04:15. As of now I have been using
long unixTime = System.currentTimeMillis() / 1000L;
Date time=new java.util.Date((long)unixTime*1000);
Calendar cal = Calendar.getInstance();
cal.setTime(time);
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
currentTime = (hours+":"+minutes+":"+seconds);
Which gives 9:4:15 instead. What is the best way to solve this?
Thanks
java.time
Much of the java.time functionality built into Java 8 & 9 and later is back-ported to Java 6 & 7 in the ThreeTen-BackPort project and further adapted to Android in the ThreeTenABP project.
Use next code:
Keep it simple: No calendar required, no div by 1000 and then multiply again, just do:
will print
adding leading zeros
You can use
SimpleDateFormat
, e.g.:Use simpledateformat method