Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

java - Getting difference between two dates 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...