Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting difference between two dates Android

Tags:

java

date

android

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.

like image 947
Udaykiran Avatar asked Aug 01 '11 10:08

Udaykiran


People also ask

How can I get the difference between two dates in days in Android?

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.

How do you find the difference between two dates in Kotlin?

This is what I do: long diff = date1. getTime() - date2. getTime(); Date diffDate = new Date(diff);

How can I get current date and time in Android?

Date; Date currentTime = Calendar. getInstance(). getTime();


2 Answers

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();
}
like image 127
Lawrence Barsanti Avatar answered Oct 14 '22 20:10

Lawrence Barsanti


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));
    }
like image 39
ShineDown Avatar answered Oct 14 '22 20:10

ShineDown