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
You can use SimpleDateFormat
, e.g.:
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
Calendar calendar = Calendar.getInstance();
System.out.println(dateFormat.format(calendar.getTime()));
Keep it simple:
No calendar required, no div by 1000 and then multiply again, just do:
Date time = new java.util.Date(System.currentTimeMillis());
System.out.println(new SimpleDateFormat("HH:mm:ss").format(time));
will print
13:04:19
adding leading zeros
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
Use simpledateformat method
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Use next code:
currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime());
java.time
LocalTime.now()
.toString()
09:04:15
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.