Custom Dates in Android ListView (Java Formatting)

ぐ巨炮叔叔 提交于 2019-12-13 01:28:05

问题


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?


回答1:


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.




回答2:


You can use PrettyTime to achieve that.

For saving time, I usually save time in millis.




回答3:


Try DateUtils.getRelativeTimeSpanString to format the date for display.



来源:https://stackoverflow.com/questions/12253332/custom-dates-in-android-listview-java-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!