Am having string posting date like :
2011-03-27T09:39:01.607
and There is current date .
I want to get difference between these two dates in the form of :
2 days ago
1 minute ago etc..
depending posting date.
Am using this code to convert posting date to milliseconds:
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();
}
this current date: long now = System.currentTimeMillis();
and to calculate difference:
String difference = (String) DateUtils.getRelativeTimeSpanString(time,now, 0);
But it returning like May 1 , 1970
or something ..
How to get the difference between posting date and current date.
startDateValue = new Date(startDate); endDateValue = new Date(endDate); long diff = endDateValue. getTime() - startDateValue. getTime(); long seconds = diff / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = (hours / 24) + 1; Log.
This is what I do: long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);
Date; Date currentTime = Calendar. getInstance(). getTime();
You can use getRelativeTimeSpanString(). It returns a string like "1 minute ago". Here is a real simple example that tells how long the application has been running.
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();
}
Convert both dates into calender and make time 0(
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
).
Then use this fun :
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With