7

I've been trying to find the answer to this for a while today and there's just so much contradictory information....

What I'd like to do is get a current unix timestamp in android, and then convert it to a format that allows me to getHours() and getMinutes().

I'm currently doing this:

int time = (int) (System.currentTimeMillis()); Timestamp ts = new Timestamp(time); mHour = ts.getHours(); mMinute = ts.getMinutes(); 

But it's not giving me a correct value for hour or minute (it's returning 03:38 for the current East-coast time of 13:33).

4 Answers 4

9

This works:

final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); Date date = cal.getTime(); mHour = date.getHours(); mMinute = date.getMinutes(); 
Sign up to request clarification or add additional context in comments.

3 Comments

Doing this returns a time of 07:00. Is it just that my device's system time is screwed up?
OK, got it. I was storing the timestamp in an int, when it really has to be a Long. Thanks guys
date.getHours, date.getMinutes, etc.. are deprecated in Android. Use @mbaird's answer
8

Just use the Java Calendar class.

Calendar c = new GregorianCalendar(); // This creates a Calendar instance with the current time mHour = c.get(Calendar.HOUR); mMinute = c.get(Calendar.MINUTE); 

Also note that your Android emulator will return times in GMT for the current time. I advise testing this type of code on a real device.

Comments

2
int time = (int) (System.currentTimeMillis()); 

here you should use long instead of int.

Comments

0

Use Time class form Google it is the best for this kind of job specialy it has good performance not like Calendar.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.