前言
本篇文章主要 讲解的是有关时间转换的问题,本篇文章主要涉及到字符串转时间戳、时间戳转字符串等相关的转换
代码如下(示例):
/** * 时间戳转换成字符窜 * @param pattern 时间样式 yyyy-MM-dd HH:mm:ss * @return [String] 时间字符串 */ @SuppressLint("SimpleDateFormat") fun Long.toDateStr(pattern: String = "yyyy-MM-dd HH:mm:ss"): String { val date = Date(this) val format = SimpleDateFormat(pattern) return format.format(date) }/** * 将字符串转为时间戳 * @param pattern 时间样式 yyyy-MM-dd HH:mm:ss * @return [String] 时间字符串 */ fun String.toDateLong(pattern: String = "yyyy-MM-dd HH:mm:ss"): Long { @SuppressLint("SimpleDateFormat") val dateFormat = SimpleDateFormat(pattern) var date: Date? = Date() try { date = dateFormat.parse(this) } catch (e: Exception) { e.printStackTrace() } return date?.time ?: 0 }/** * 根据年月日获取时间戳 * @param year 年 * @param month 月 * @param day 日 * @return [Long] 时间戳 */ fun getDateFromYMD(year: Int = curYear, month: Int = curMonth, day: Int = curDay): Long { return getDateFromYMDHMS(year, month, day, 0, 0, 0) }/** * 根据年月日时分秒获取时间戳 * @param year Int 年 * @param month Int 月 * @param day Int 日 * @param hour Int 时 * @param minute Int 分 * @param second Int 秒 * @return [Long] 时间戳 */ fun getDateFromYMDHMS( year: Int = curYear, month: Int = curMonth, day: Int = curDay, hour: Int = curHour, minute: Int = curMinute, second: Int = curSecond ): Long { val calendar = Calendar.getInstance() calendar.set(year, month - 1, day, hour, minute, second) calendar.set(Calendar.MILLISECOND, 0) return calendar.timeInMillis }
总结
例如:以上就是今天要讲的内容,本文仅仅简单介绍了时间转换的使用,而对于时间的转换还有很多的使用方法,下篇文章继续讲解有关时间的各种使用。