android 时间工具类
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()
/**
* 计算两个时间戳的差值,单位是天
* */
fun calculateDaysDifference(timestamp1: Long, timestamp2: Long): Int {
val calendar1 = Calendar.getInstance()
val calendar2 = Calendar.getInstance()
val date1 = Date(timestamp1)
calendar1.time = date1
val date2 = Date(timestamp2)
calendar2.time = date2
val day1 = calendar1.get(Calendar.DAY_OF_MONTH)
val day2 = calendar2.get(Calendar.DAY_OF_MONTH)
// 将差值从毫秒转换为天
return day2 - day1
}
fun calculateDaysDifferenceString(timestamp1: String, timestamp2: String) : Long{
// 定义时间格式
val format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
// 将时间戳字符串转换为 LocalDateTime 对象
val dt1 = LocalDateTime.parse(timestamp1, format)
val dt2 = LocalDateTime.parse(timestamp2, format)
// 计算时间差
val duration = Duration.between(dt1, dt2)
// 计算差的天数,只要过了24小时就算差1天
val daysDifference = duration.toDays() + if (duration.seconds % 86400 > 0) 1 else 0
return daysDifference
}
fun calculateDayDifferenceV2(timestamp1: Long, timestamp2: Long): Long {
// 计算时间差(以毫秒为单位)
val diffInMillis = timestamp2 - timestamp1
// 计算差的天数,只要过了24小时就算差1天
val daysDifference = TimeUnit.MILLISECONDS.toDays(diffInMillis) + if (diffInMillis % TimeUnit.DAYS.toMillis(1) > 0) 1 else 0
return daysDifference
}
}
}
原文地址:https://blog.csdn.net/Steve_XiaoHai/article/details/140466759
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!