android时间工具--多久之前

在开发新闻客户端的时候,是在会显示时间是多久之前,比如10分钟前,8小时前,一月前等等。
下面是一个简单的实现:

import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
    private final static long minute = 60 * 1000;// 1分钟
    private final static long hour = 60 * minute;// 1小时
    private final static long day = 24 * hour;// 1天
    private final static long month = 31 * day;// 月
    private final static long year = 12 * month;// 年

    private void testDiffDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = null;
        try {
            d = sdf.parse("2016-02-16 09:57:18");
            Log.i("DateUtil", "testDate: " + d.getTime());
            long diff = new Date().getTime() - d.getTime();
            Log.i("DateUtil", "testDate: " + d.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long diff = new Date().getTime() - d.getTime();
        long r = 0;
        if (diff > year) {
            r = (diff / year);
            Log.i("DateUtil", "testDate: " + r + "年前");
        } else if (diff > month) {
            r = (diff / month);
            Log.i("DateUtil", "testDate: " + r + "个月前");
        } else if (diff > day) {
            r = (diff / day);
            Log.i("DateUtil", "testDate: " + r + "天前");
        } else if (diff > hour) {
            r = (diff / hour);
            Log.i("DateUtil", "testDate: " + r + "个小时前");
        } else if (diff > minute) {
            r = (diff / minute);
            Log.i("DateUtil", "testDate: " + r + "分钟前");
        } else
            Log.i("DateUtil", "testDate: 刚刚");
    }
}

你可能感兴趣的:(Android开发)