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的格式时间不统一。

0efde3cbf5289fb57a1fa30dd20d783b.png

正确情况:

先通过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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值