Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Convert System.currentTimeMillis To Time Format? (HH:MM:SS) [duplicate]

Tags:

java

android

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!

like image 273
cryptic_coder Avatar asked May 06 '19 14:05

cryptic_coder


People also ask

How do you convert MS to HH mm SS?

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.

What is the output of system currentTimeMillis ()?

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.

How do you convert milliseconds to time?

Convert Milliseconds to minutes using the formula: minutes = (milliseconds/1000)/60). Convert Milliseconds to seconds using the formula: seconds = (milliseconds/1000)%60).

How do you convert HH mm SS to seconds in Java?

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date reference = dateFormat. parse("00:00:00"); Date date = dateFormat. parse(string); long seconds = (date. getTime() - reference.


1 Answers

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
like image 171
MohammadL Avatar answered Oct 05 '22 10:10

MohammadL