Android常用的时间转换之字符串转时间戳

前言

本篇文章主要 讲解的是有关时间转换的问题,本篇文章主要涉及到字符串转时间戳、时间戳转字符串等相关的转换

代码如下(示例):

/**
 * 时间戳转换成字符窜
 * @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
}

总结

例如:以上就是今天要讲的内容,本文仅仅简单介绍了时间转换的使用,而对于时间的转换还有很多的使用方法,下篇文章继续讲解有关时间的各种使用。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值