//将时间毫秒值转化为年月日
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