作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 Android 开发新手。
我需要一个帮助来将我的当前时间转换为一个静态时间。
感谢您的帮助。
我有一个这样的字符串
String created_at = "Wed Mar 03 19:37:35 +0000 2010";
我想将其转换为 ,这意味着我的当前时间和created_at字符串之间的差异。
23 mins ago // Example
谢谢
达米克
最佳答案
只需使用我创建的以下实用程序类并在其构造函数中传递两个日期对象。随后使用 getDifferenceString() 方法获取相同的结果。
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Date curdate, Date olddate) {
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? " year" : " years") + " ago");
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? " month" : " months") + " ago");
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? " day" : " days") + " ago");
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? " hour" : " hours") + " ago");
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? " minute" : " minutes") + " ago");
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? " second" : " seconds") + " ago");
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
关于java - 需要与 "A Min ago"或 "An Hour Ago"等字符串的时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24780474/
我是一名优秀的程序员,十分优秀!