欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

android获取毫秒,Android 日期转为为毫秒,毫秒转化为日期,获取当期日期年、月、日...

发布时间:2025/3/20 53 豆豆
生活随笔 收集整理的这篇文章主要介绍了 android获取毫秒,Android 日期转为为毫秒,毫秒转化为日期,获取当期日期年、月、日... 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

//将时间毫秒值转化为年月日

val date = Date(System.currentTimeMillis())

val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())

val dateStr = simpleDateFormat.format(date)

OLogsProUtil.e("测试:" + dateStr)

//将日期转化为毫秒值

val simpleDateFormat1 = SimpleDateFormat("yyyy-MM-dd HH:mm")

val date1 = simpleDateFormat1.parse("2020-09-20 09:47")

val timeLong = date1.time

OLogsProUtil.e("测试:" + timeLong)

//将日期转化为星期、获取年月日

val date2 = Date(System.currentTimeMillis())

val calendar = Calendar.getInstance()

calendar.time = date2

//星期

val weekDay = calendar.get(Calendar.DAY_OF_WEEK)-1

//年

val year = calendar.get(Calendar.YEAR)

//月

val month = calendar.get(Calendar.MONTH)+1

//日

val monthDay = calendar.get(Calendar.DAY_OF_MONTH)

OLogsProUtil.e("测试:星期" + weekDay+"."+year+"-"+month+"-"+monthDay)

将日期转化为毫秒主要使用的是SimpleDateFormat.parse()。使用时需要注意的是:

使用SimpleDateFormat.parse()的时候,经常会有ParseException发生,原因是输入的字符串格式跟SimpleDateFormat定义的格式不一致。

这时候,可以先通过SimpleDateFormat.format把参数转成符合格式的字符串,然后再调用SimpleDateFormat.parse()

比如:

错误情况:

一、

val simpleDateFormat3 = SimpleDateFormat("yyyy-MM-dd HH:mm")

val date3 = Date(System.currentTimeMillis())

val parse = simpleDateFormat3.parse(date3.toString())

二、

val simpleDateFormat1 = SimpleDateFormat("yyyy-MM-dd HH:mm")

val date1 = simpleDateFormat1.parse("2020-09-20")

val timeLong = date1.time

这两种情况

“val parse = simpleDateFormat3.parse(date3.toString())”

“val date1 = simpleDateFormat1.parse("2020-09-20")”

这两行都会报ParseException,因为与SimpleDateFormat的格式时间不统一。

正确情况:

先通过SimpleDateFormat.format把参数转成符合格式的字符串,然后再调用SimpleDateFormat.parse()

//将日期转化为毫秒值

val simpleDateFormat3 = SimpleDateFormat("yyyy-MM-dd HH:mm")

try {

val date3 = Date(System.currentTimeMillis())

val format_date = simpleDateFormat3.format(date3)

val parse_date = simpleDateFormat3.parse(format_date)

val time_date = parse_date.time

OLogsProUtil.e("测试:正确毫秒是" + time_date)

} catch (e: ParseException) {

OLogsProUtil.e("error")

}

本文地址:https://blog.csdn.net/NewActivity/article/details/108846204

总结

以上是生活随笔为你收集整理的android获取毫秒,Android 日期转为为毫秒,毫秒转化为日期,获取当期日期年、月、日...的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。