I am trying to convert System.currentTimeMillis to current time format of (hh:mm:ss). So far this is what I've tried and it's not working right.
Long currentTime = System.currentTimeMillis();
int hours;
int minutes;
int seconds;
String getSecToStr = currentTime.toString();
String getTimeStr = getSecToStr.substring(8,13);
seconds = Integer.parseInt(getTimeStr);
minutes = seconds / 60;
seconds -= minutes * 60;
hours = minutes / 60;
minutes -= hours * 60;
String myResult = Integer.toString(hours) + ":" + Integer.toString(minutes) + ":" + Integer.toString(seconds);
System.out.println("Current Time Is: " + myResult);
Any ideas? Much appreciated!
So if a millisecond 1/1000th of a second then there are 60,000 milliseconds in a minute, 3,600,000 milliseconds in an hour and 86,400,000 in a day. So all you need to do is divide the data you have in milliseconds by 86,400,000. Format the result as [h]:mm:ss and you are done.
currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date reference = dateFormat. parse("00:00:00"); Date date = dateFormat. parse(string); long seconds = (date. getTime() - reference.
There are some object that you can use to make this more easy, like SimpleDateFormat
and Date
.
First prepare the time in mills:
Long currentTime = System.currentTimeMillis();
Choose your desier format with SimpleDateFormat
:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");
Create your date object:
Date date = new Date(currentTime);
Apply that format into your date object:
String time = simpleDateFormat.format(date);
Log it:
Log.d(TAG, "onCreate: " + time);
Result:
17:05:73
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With