Java 两次约会的区别
我有字符串发布日期,如:Java 两次约会的区别,java,android,date,Java,Android,Date,我有字符串发布日期,如: 2011-03-27T09:39:01.607 还有当前日期 我想以以下形式得出这两个日期之间的差异: 2 days ago 1 minute ago etc.. 取决于投寄日期 我使用此代码将过帐日期转换为毫秒: public long Date_to_MilliSeconds(int day, int month, int year, int hour, int minute) { Calendar c = Calendar.getInstance()
2011-03-27T09:39:01.607
还有当前日期
我想以以下形式得出这两个日期之间的差异:
2 days ago
1 minute ago etc..
取决于投寄日期
我使用此代码将过帐日期转换为毫秒:
public long Date_to_MilliSeconds(int day, int month, int year, int hour, int minute) {
Calendar c = Calendar.getInstance();
c.set(year, month, day, hour, minute, 00);
return c.getTimeInMillis();
}
当前日期:long now=System.currentTimeMillis()代码>
并计算差异:
String difference = (String) DateUtils.getRelativeTimeSpanString(time,now, 0);
但是它像1970年5月1日之类的
如何获取过帐日期和当前日期之间的差异。将两个日期转换为日历,并使时间为0(
).
然后用这个有趣的方法:
public final static long SECOND_MILLIS = 1000;
public final static long MINUTE_MILLIS = SECOND_MILLIS*60;
public final static long HOUR_MILLIS = MINUTE_MILLIS*60;
public final static long DAY_MILLIS = HOUR_MILLIS*24;
public static int daysDiff( Date earlierDate, Date laterDate )
{
if( earlierDate == null || laterDate == null ) return 0;
return (int)((laterDate.getTime()/DAY_MILLIS) - (earlierDate.getTime()/DAY_MILLIS));
}
你得到1970的原因是因为它是以毫秒为单位的纪元日期。要获得实际差异,请使用以下公式
使用你可以使用的。它返回一个类似“1分钟前”的字符串。下面是一个真正简单的示例,说明应用程序已经运行了多长时间
private long mStartTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mStartTime = System.currentTimeMillis();
}
public void handleHowLongClick(View v) {
CharSequence cs = DateUtils.getRelativeTimeSpanString(mStartTime);
Toast.makeText(this, cs, Toast.LENGTH_LONG).show();
}
尝试我在其中一个应用程序中使用的以下方法:
/**
* Returns difference between time and current time as string like:
* "23 mins ago" relative to current time.
* @param time - The time to compare with current time in yyyy-MM-dd HH:mm:ss format
* @param currentTime - Present time in yyyy-MM-dd HH:mm:ss format
* @return String - The time difference as relative text(e.g. 23 mins ago)
* @throws ParseException
*/
private String getTimeDiff(String time, String currentTime) throws ParseException
{
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = (Date)formatter.parse(currentTime);
Date oldDate = (Date)formatter.parse(time);
long oldMillis = oldDate.getTime();
long currentMillis = currentDate.getTime();
return DateUtils.getRelativeTimeSpanString(oldMillis, currentMillis, 0).toString();
}
实现这一点的简单方法:
在项目中导入joda库
将当前日期和未来日期存储在变量中,如下所示
//here currenDate and futureDate are of calendar type.
LocalDateTime currentDateTime = LocalDateTime.fromCalendarFields(currentDate);
LocalDateTime futureDateTime = LocalDateTime.fromCalendarFields(futureDate);
现在你要做的是计算两个日期之间的差异并保存差异,这个差异将用于从下一个字段中减去
例如:我们必须显示年、月、周……等等。在计算了两个日期之间的年数之后,我们将减去月份中的年数,同样,对于下一个字段,日期时间的层次结构如下所示
年月周日时分秒
现在是片段
/**
*
* @param context which activity its calling
* @param currentDateTime current time
* @param futureDateTime future time from which we have to calculate difference
* @param selectedUnitsFromSettings which units we have to find difference such as years,weeks....etc
* which will be stored in list...
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static HashMap dateBasedOnUnitCalculator(
Context ctx, LocalDateTime currentDateTime,
LocalDateTime futureDateTime, List<String> selectedUnitsFromSettings) {
//to store the dates
Date currentTime = currentDateTime.toDateTime().toDate();
Date futureTime = futureDateTime.toDateTime().toDate();
//to store the units
String currentUnit = "";
String prevUnit = "";
//to store the value which you want to remove
int prevValue = 0;
//to store the calculated values in hashmap
HashMap units = new HashMap();
for(int i = 0; i < selectedUnitsFromSettings.size(); i++){
//to store the current unit for calculation of future date
currentUnit = selectedUnitsFromSettings.get(i);
//to remove higher unit from new future date we will use prevUnit
if(i > 0){
prevUnit = selectedUnitsFromSettings.get(i-1);
futureTime = getDateForPreviousUnit(futureTime,prevUnit,prevValue);
}
//now calculate the difference
if(currentUnit.equals("Year")){
Years q = Years.yearsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
int years = q.getYears();
prevValue = years;
units.put("Year", prevValue);
}else if(currentUnit.equals("Month")){
Months w = Months.monthsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
int months = w.getMonths();
prevValue = months;
units.put("Month", prevValue);
}else if(currentUnit.equals("Week")){
Weeks e = Weeks.weeksBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
int weeks = e.getWeeks();
prevValue = weeks;
units.put("Week", prevValue);
}else if(currentUnit.equals("Day")){
Days r = Days.daysBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
int days = r.getDays();
prevValue = days;
units.put("Day", prevValue);
}else if(currentUnit.equals("Hour")){
Hours a = Hours.hoursBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
int hours = a.getHours();
prevValue = hours;
units.put("Hour", prevValue);
}else if(currentUnit.equals("Minute")){
Minutes s = Minutes.minutesBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
int minutes = s.getMinutes();
prevValue = minutes;
units.put("Minute", prevValue);
}else if(currentUnit.equals("Second")){
Seconds d = Seconds.secondsBetween(new DateTime(currentTime.getTime()), new DateTime(futureTime.getTime()));
int seconds = d.getSeconds();
prevValue = seconds;
units.put("Second", prevValue);
}
}
return units;
}
现在要从任何活动调用,请使用此
HashTable hashTable = dateBasedOnUnitCalculator(this, currentDateTime, futureDateTime, selectedUnitsFromSettings);
//to display the values from hashtable
showLog(TAG,
" year "+hashTable.get("Year") +
" month "+hashTable.get("Month") +
" week "+hashTable.get("Week") +
" day "+hashTable.get("Day") +
" hours "+hashTable.get("Hour") +
" min " +hashTable.get("Minute") +
" sec " +hashTable.get("Second") +
" ");
从设置中选择的单位将具有您想要的任何单位
您可以在不使用任何库的情况下找到两个日期之间的差异
您只需找出以下日期之间的差异:
long diff = currentdate.getTime() - temp_date.getTime();
//current date //other date
通过这个,你将得到毫秒级的差异。。
现在,您可以根据您的需要格式化此文件,即在小时前、数月前或数年前格式,只需使用if条件即可
请参阅完整示例
希望对你有帮助 Joda time是一个500kb+的库,可能不适合Android应用程序。@Jonny:你还有其他合适的选择要讨论吗?是的,实际上Lawrence Barsanti下面的答案更适合使用Android time类的Android。它提供了OP要求的格式的字符串。+1用于使用Android API!这应该是公认的答案!哦,太好了,这对我有帮助。。在没有库osm的情况下获取日期
HashTable hashTable = dateBasedOnUnitCalculator(this, currentDateTime, futureDateTime, selectedUnitsFromSettings);
//to display the values from hashtable
showLog(TAG,
" year "+hashTable.get("Year") +
" month "+hashTable.get("Month") +
" week "+hashTable.get("Week") +
" day "+hashTable.get("Day") +
" hours "+hashTable.get("Hour") +
" min " +hashTable.get("Minute") +
" sec " +hashTable.get("Second") +
" ");
long diff = currentdate.getTime() - temp_date.getTime();
//current date //other date