class MainActivity extends Activity {
private TextView dates;
private SimpleDateFormat d;
private String nowtime;
private String testtime;
/**
* (非 Javadoc)
* <p>Title: onCreate</p>
* <p>Description: </p>
* @param savedInstanceState
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dates = (TextView)findViewById(R.id.date);
d= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间
nowtime=d.format(new Date());//按以上格式 将当前时间转换成字符串
testtime="2014-04-10 12:45:35";//测试时间
String str=null;
try {
str = dateToRelativeTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dates.setText(str);
}
/**
* @Title: dateToRelativeTime
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @return
* @param @throws ParseException 设定文件
* @return String 返回类型
* @throws
*/
private String dateToRelativeTime() throws ParseException{
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now=new Date();
long between=(d.parse(nowtime).getTime()-d.parse(testtime).getTime())/1000;//当前时间减去测试时间 这个的除
long day=between/(24*3600);
long hour=between%(24*3600)/3600;
long minute=between%3600/60;
long second=between;
String timeStr;
if(day>0&&day<=29){
timeStr=day+"天前";
}else if(day>29){
timeStr=df.format(now);
}else{
if(hour>0){
timeStr=hour+"小时前";
}else{
if(minute>0){
timeStr=minute+"分钟前";
}else{
timeStr=second+"秒前";
}
}
}
return timeStr;
}
}