Badr Hari
Badr Hari

Reputation: 8384

Android Time class - Milliseconds back to Time?

This is what I have... if I convert it to milliseconds I have to store it as long. I use Android API Time class (http://developer.android.com/reference/android/text/format/Time.html)

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
long todayMillis = today.toMillis(false);

I would like to format it back after to readable version something like that (after getting teh milliseconds I save it to the database to retrieve it afterwards):

todayMillis.format("%k:%M %d.%m.%y");

But I can't do it so easily since I need to convert back to Time.. how can it be done?

Upvotes: 2

Views: 1452

Answers (3)

bpichon
bpichon

Reputation: 46

Try this:

Calendar calendar = Calendar.getInstance(); // Creates a new Calendar with the current Time
calendar.setTimeInMillis(todaysMillis);  // you can also put your millis in. Same effect.
String readableOutput = calendar.get(Calendar.HOUR_OF_DAY) +
            ":" + calendar.get(Calendar.MINUTE) +
            " " + calendar.get(Calendar.DAY_OF_MONTH) +
            "." + (1+calendar.get(Calendar.MONTH)) +
            "." + calendar.get(Calendar.YEAR);

For more Fields and Methods: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94459

You already have the today object of type Time so there is no need to convert the millis back to time. But if you must, android.text.format.Time contains a set method that takes milliseconds as a long.

Time newToday = new Time();
newToday.set(todayMillis);
newToday.format("%k:%M %d.%m.%y");

Documentation

Upvotes: 1

William Morrison
William Morrison

Reputation: 11006

Create a new time object, then call Time.set(long milliseconds)

Time time = new Time(Time.getCurrentTimeZone());
time.set(todayMillis);

I don't think the original time zone is even needed as the milliseconds are in UTC, however I'm guess the Time object uses the passed time zone internally somehow.

Upvotes: 4

Related Questions