/**
* 時間格式化
* 參數:
* time:時間
* type:
* 0 -> 今天10:20 昨天10:20 2019.01.21 10:29
* 1 -> 10:20 昨天10:20 2019.01.21 10:29
* 2 -> 2019.01.21 10:29
* 3 -> 2019.01.21
* 4 -> 10:29
* 5 -> 今天10:20 2019.01.21 10:29
*/
private fun commonTime(time: Long, type: Int = 0): String {
var calendar = Calendar.getInstance()
calendar.timeInMillis = time
var year = calendar.get(Calendar.YEAR) // .toString().subSequence(2, 4)
var month = String.format("%02d", calendar.get(Calendar.MONTH) + 1)
var day = String.format("%02d", calendar.get(Calendar.DATE))
var hour = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY))
var minute = String.format("%02d", calendar.get(Calendar.MINUTE))
return when (type) {
2 -> {
return "$year.$month.$day $hour:$minute"
}
3 -> {
return "$year.$month.$day"
}
4 -> {
return "$hour:$minute"
}
5 -> {
var days = differentDays(System.currentTimeMillis(), time)
when (days) {
0 -> {
return "${"今天 "}$hour:$minute"
}
}
return "$year.$month.$day $hour:$minute"
}
6 -> {
return "${month}月"
}
7 -> {
return "${year}年${month}月"
}
else -> {
var days = differentDays(System.currentTimeMillis(), time)
when (days) {
0 -> {
return "${if (type == 1) "" else "今天 "}$hour:$minute"
}
1 -> {
return "明天 $hour:$minute"
}
-1 -> {
return "昨天 $hour:$minute"
}
}
return "$year.$month.$day $hour:$minute"
}
}
}
/**
* date2比date1多的天數
* @param time1
* @param time2
* @return
*/
fun differentDays(time1: Long, time2: Long): Int {
val cal1 = Calendar.getInstance()
cal1.timeInMillis = time1
val cal2 = Calendar.getInstance()
cal2.timeInMillis = time2
val day1 = cal1.get(Calendar.DAY_OF_YEAR)
val day2 = cal2.get(Calendar.DAY_OF_YEAR)
val year1 = cal1.get(Calendar.YEAR)
val year2 = cal2.get(Calendar.YEAR)
if (year1 != year2) {
var timeDistance = 0
for (i in year1 until year2) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
timeDistance += 366
} else {
timeDistance += 365
}
}
return timeDistance + (day2 - day1)
} else {
return day2 - day1
}
}
/**
* 是否爲今年
*/
fun isToYear(time: Long): Boolean {
val pre = Calendar.getInstance()
val predate = Date(System.currentTimeMillis())
pre.time = predate
val cal = Calendar.getInstance()
cal.time = Date(time)
if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) {
return true
}
return false
}
/**
* 秒轉換爲分
* Math.ceil()執行向上舍入
* Math.floor()執行向下舍入
* Math.round()四捨五入
*/
private fun changeS2M(second: Long): String {
val m = Math.round(second / 60.0).toInt()
return m.toString()
}
/**
* 時間格式轉long
* 2018-08-20 14:53:37時間格式 -> 時間戳
*/
@SuppressLint("SimpleDateFormat")
@JvmStatic
fun timeStringToLong(time: String?): Long {
try {
return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).time
} catch (e: Exception) {
e.printStackTrace()
}
return Date().time
}