Java 计算两个日期时间差,天数、时、分、秒

本文介绍了一种计算宠物年龄的方法,通过比较宠物出生日期与当前日期来确定宠物的年龄,并将其转换为年、月、日的形式进行展示。此外,还提供了一个计算两个指定日期之间时间差的实用函数。
public static String getCurrentTimeString() {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",
            Locale.getDefault());
    String currentTime = sdf.format(date);
    return currentTime;
}

private fun dealWithPetAge(birthTime: String,tv_pet_birth :TextView) {
    val dayDiffer: Int =
        AppUtils.getDifferTime(birthTime, AppUtils.getCurrentTimeString()) + 1 //当天显示为1天
    AppLog.Loge(
        ("----lgq宠物出生的日期:" + birthTime + "-----当前的时间:" + AppUtils.getCurrentTimeString()) +
                "------相隔时间:" + dayDiffer + "天"
    )
    if (dayDiffer < 30) {
        val day = dayDiffer
        tv_pet_birth.setText(day.toString() + LangComm.getString("day"))
    } else if (dayDiffer < 365) {
        val mouth = dayDiffer / 30
        val day = dayDiffer - mouth * 30
        tv_pet_birth.setText(mouth.toString() + LangComm.getString("pet_mouth"))
    } else {
        val year = dayDiffer / 365
        val mouth = (dayDiffer - year * 365) / 30
        val day = dayDiffer - (year * 365) - (mouth * 30)
        tv_pet_birth.setText(year.toString() + " " + LangComm.getString("age_year"))
    }
}

计算时间差方法

    public static int getDistanceTimemin(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;//天数差
        long hour = 0;//小时数差
        long min = 0;//分钟数差
        long second=0;//秒数差
        try {

            final Calendar c = Calendar.getInstance();
            c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));

            one = df.parse(str1);
            c.setTime(one);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            diff = time2 - time1;

            day = diff / (24 * 60 * 60 * 1000);
//            Log.i("lgq","diff--==="+diff+"...one="+time1+"..-----.two==="+time2);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            second = diff/1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (int)min;
    }
second =((diff / (1000)) - day * 24 * 60*60 - hour * 60*60-min*60);

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值