Frage

I'm using Android, trying to implement something that will tell me how long ago someone played a game. This is what I have:

Date date;

try {
    date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(g.getLastPlayed());
    long milliseconds = date.getTime();
    long timeNow = new Date().getTime();
    DateUtils.
    String timeSince = (String) DateUtils.getRelativeTimeSpanString (milliseconds, timeNow, DateUtils.MINUTE_IN_MILLIS);
    TextView timeAgo = (TextView) convertView.findViewById(R.id.current_game_last_played_text);
    timeAgo.setText(timeSince + " " + timeNow);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

I'm having a few problems with different routes I've tried:

One way I tried was to have my rows in the database be DATETIMES and that's what you see I'm doing in the first line of the try. Converting it to a SimpleDateFormat, so I can call getTime after that and get the milliseconds. That appeared to be working fine on my emulator but then when I put it on my phone I was getting MUCH different results. I did some debugging and realized that the milliseconds was being calculated differently based on whether I was on an emulator, a phone, or a Kindle.

Is there any way I can make milliseconds always be the same value no matter what device it was on?

Another thing I noticed, is it seems like the values from getTime are actually wrong. In MySQL when I do UNIX_TIMESTAMP(now()) it gives me a result like:

1391732897

While getTime back in Java gets me something like this:

1391732385372

Why is the Java one so much longer?

War es hilfreich?

Lösung 2

I guess the problem is related to timezone. Date.getTime() returns value in UTC (Greenwich) time, if the string returned by getLastPlayed() is in local time, the difference can be many hours (depending on your timezone) even if you played 1 second ago.

Andere Tipps

MySQL's UNIX_TIMESTAMP() gives the time in seconds, while Java's new Date().getTime() gives the time in milliseconds.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top