主要事项:
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()
}
}
}