Convert time format to long variable in Java

1.5k views Asked by At

Is there a possibility to convert a time format which is represented as a string (00:00:000) to long variable.

2

There are 2 answers

1
ninja.coder On BEST ANSWER

I'm not sure what do you mean by Convert to currentTimeMillis() or some float variable., but if you are simply looking to convert the given time to long then you can do something like this using simple split:

String timeString = "01:00:100";
int multiplier[] = {3600000, 60000, 100};
String splits[] = timeString.split(":");
long time = 0;
for (int x = 0; x < splits.length; x++) {
    time += (Integer.parseInt(splits[x]) * multiplier[x]);
}
System.out.println(time);

Here, the time is being represented in Milliseconds.

Also, this is plain Java and nothing Android specific.

0
GhostCat On

That simply doesn't make much sense.

currentTimeMillis() returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

In other words: the result of a call to that method represents a full blown time stamp; not only hh::mm:sss as in your example; but all of that plus year, month, ...

Thus the answer here: you should step back and clarify for yourself what your actual requirements are.