TheLettuceMaster
TheLettuceMaster

Reputation: 15734

Custom Dates in Android ListView (Java Formatting)

I have a ListView that users will put comment in. When they hit "submit" attached to an EditText box, the new comment goes into a MySQL database along with the current time.

I'd like the comments to appear in the listview with dates similar to Youtube formatting. For example: "10 seconds ago", "1 day ago", "52 days ago".

Would I use the Calendar object, SimpleDateFormat, something else?

Also, how would I store the date in the datebase? I am assuming something easily convertible like the UNIX date stamp maybe. And then would it be in the ArrayAdapter where I dynamically change the date based on the current time?

Upvotes: 1

Views: 542

Answers (3)

Nick Bradbury
Nick Bradbury

Reputation: 1745

Try DateUtils.getRelativeTimeSpanString to format the date for display.

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

To get this you need to calculate the difference between your timestamp and current timestamp (keep them in milliseconds for simplicity). The result will be number of milliseconds "ago". Then use simple math like subtraction and division and you can get number of minutes, days, weeks and whatever-you-want.

EDIT: I use this:

public static final long MILLIS_PER_SECOND  = 1000;
public static final long MILLIS_PER_MINUTE  = (MILLIS_PER_SECOND * 60);
public static final long MILLIS_PER_HOUR    = (MILLIS_PER_MINUTE * 60);
public static final long MILLIS_PER_DAY     = (MILLIS_PER_HOUR * 24);
public static final long MILLIS_PER_WEEK    = (MILLIS_PER_DAY * 7);
public static final long MILLIS_PER_MONTH   = (MILLIS_PER_DAY * 30);
public static final long MILLIS_PER_YEAR    = (MILLIS_PER_MONTH * 12);

Note that is is not 100% correct as I (intentionally, for simplicy) made false assumption month is always 30 days long, which also influences MILLIS_PER_YEAR. But I do not really care - it's not rocket science I use these for. But you may reduce the impact by setting MILLIS_PER_YEAR this way:

public static final long MILLIS_PER_YEAR = (MILLIS_PER_DAY * (7*31 + 4*30 + 28));

28 is for February, in this case you only be 1 day off on leaps years, instead of 5 days as in former version.

Upvotes: 1

Sayyam
Sayyam

Reputation: 959

You can use PrettyTime to achieve that.

For saving time, I usually save time in millis.

Upvotes: 2

Related Questions