Bonhomme
Bonhomme

Reputation: 33

System.currentTimeMillis() giving wrong time in hours

I'm trying to get my app to display a time, and for that I need to get the android's minutes and hours. I'm trying to use currentTimeMillis(), but I'm getting the wrong number for the hours. Here's my code for the hours and minutes using the systems clock.

    int defday = (int) (System.currentTimeMillis() / (1000 * 60 * 60 * 24));
    int defhour = (int) (System.currentTimeMillis() - (defday * 1000 * 60 * 60 * 24))
            / (1000 * 60 * 60);
    int defmin = (int) (System.currentTimeMillis()
            - (defhour * 1000 * 60 * 60) - (defday * 1000 * 60 * 60 * 24))
            / (1000 * 60);

After I run the app, the time shows the time as 5:36 even though the current time is 1:36. What am I doing wrong?

Upvotes: 0

Views: 3244

Answers (1)

Rakesh Soni
Rakesh Soni

Reputation: 10897

Create a Calendar object:

long millis=System.currentTimeMillis();
Calendar c=Calendar.getInstance();
c.setTimeInMillis(millis);

After this you can get the fields from the Calendar object:

int hours=c.get(Calendar.HOUR);
int minutes=c.get(Calendar.MINUTE);

Then:

int MinutesHours=(hours*60)+minutes; To go back, you can use the set method in Calendar:

Calendar c=Calendar.getInstance();
c.set(Calendar.MINUTE,minutes);
long millis=c.getTimeInMillis();

References

How to measure the a time-span in seconds using System.currentTimeMillis()?

currentTimeMillis() to Years, days, and minutes, and backwords. (hard)

Upvotes: 3

Related Questions