android 时间工具类

 主要事项:

1.时间差以24小时为间隔

举例:

2024-08-10 11:59:00到2024-08-11 11:59:00 ,时间差是1天

2024-08-10 11:59:00到2024-08-11 12:59:00 ,时间差是2天

2.时间差以日期为间隔

举例:

2024-08-10 11:59:00到2024-08-11 13:59:00 ,时间差是1天

2024-08-11 11:59:00到2024-08-11 12:59:00 ,时间差还是0天

日期是同1天,或者日期只差1天

class UtilTime {

    companion object {
private val dateFormat = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA)
        private val dateFormatYmdHms = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA)
        private val dateFormatYmd = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
        private val mCalendar = Calendar.getInstance()

/**
          /**
         * 比较两个日期是不是同一天
         * */
        private fun areTimestampsOnSameDay(start: Long, end: Long): Boolean {
            val date1 = Date(start)
            val date2 = Date(end)

            val calendar1 = Calendar.getInstance()
            calendar1.time = date1

            val calendar2 = Calendar.getInstance()
            calendar2.time = date2

            // 比较年份、月份和日期部分
            return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) &&
                    calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) &&
                    calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH)
        }

        /**
         * 计算差的天数,只要过了24小时就算差1天
         * */
        fun calculateDaysAs24HourIntervals(timestamp1: Long, timestamp2: Long): Int {
            val differenceInMillis = abs(timestamp2 - timestamp1)
            return (differenceInMillis / (1000 * 60 * 60 * 24)).toInt()
        }

        /**
         * 计算两个时间戳的差值,单位是天,以日期为天数差
         * */
        fun calculateDaysBetweenDates(timestamp1: Long, timestamp2: Long): Int {
            val calendar1 = Calendar.getInstance()
            calendar1.timeInMillis = timestamp1
            calendar1[Calendar.HOUR_OF_DAY] = 0
            calendar1[Calendar.MINUTE] = 0
            calendar1[Calendar.SECOND] = 0
            calendar1[Calendar.MILLISECOND] = 0

            val calendar2 = Calendar.getInstance()
            calendar2.timeInMillis = timestamp2
            calendar2[Calendar.HOUR_OF_DAY] = 0
            calendar2[Calendar.MINUTE] = 0
            calendar2[Calendar.SECOND] = 0
            calendar2[Calendar.MILLISECOND] = 0

            return ((calendar2.timeInMillis - calendar1.timeInMillis) / (1000 * 60 * 60 * 24)).toInt()
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值