How can we get time?
For instance:
1 min ago
1 sec ago
today
yesterday
tuesday
before 7 days (1 week ago) it must show the date.
How can we get time?
For instance:
1 min ago
1 sec ago
today
yesterday
tuesday
before 7 days (1 week ago) it must show the date.
If your'e saving the date, you can just use Period:
DateTime myDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myDate, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendSeconds().appendSuffix(" seconds ago\n")
.appendMinutes().appendSuffix(" minutes ago\n")
.appendHours().appendSuffix(" hours ago\n")
.appendDays().appendSuffix(" days ago\n")
.appendWeeks().appendSuffix(" weeks ago\n")
.appendMonths().appendSuffix(" months ago\n")
.appendYears().appendSuffix(" years ago\n")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
System.out.println(elapsed);
Prints:
3 seconds ago
51 minutes ago
7 hours ago
6 days ago
10 months ago
31 years ago
I've done a similar thing using the DateUtils.getRelativeTimeSpanString().
It will return at date once it's > 1 week
public String timeSinceNow(Date date) {
long test = date.getTime();
String result = "";
long millis = System.currentTimeMillis();
long milliseconds = (millis - test);
long minutes = 0;
long hours = 0;
long days = 0;
days = (int) (milliseconds / (1000 * 60 * 60 * 24));
hours = (int) ((milliseconds - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
minutes = (int) (milliseconds - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);
if (days > 0 || hours > 0 || minutes > 0) {
if (hours > 0) {
if (minutes > 0) {
if (days == 0) {
if (hours == 0) {
if (minutes < 3) {
result = "Now";
} else {
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
} else {
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
}
else{
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
}else{
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
}else{
result = (String) DateUtils.getRelativeTimeSpanString(test, System.currentTimeMillis(), 0);
}
} else {
result = "Now";
}
return result;
}
This will return a String with the difference between "Now" and the date you pass as a parameter