android获取毫秒,Android 日期转为为毫秒,毫秒转化为日期,获取当期日期年、月、日...
//將時(shí)間毫秒值轉(zhuǎn)化為年月日
val date = Date(System.currentTimeMillis())
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
val dateStr = simpleDateFormat.format(date)
OLogsProUtil.e("測(cè)試:" + dateStr)
//將日期轉(zhuǎn)化為毫秒值
val simpleDateFormat1 = SimpleDateFormat("yyyy-MM-dd HH:mm")
val date1 = simpleDateFormat1.parse("2020-09-20 09:47")
val timeLong = date1.time
OLogsProUtil.e("測(cè)試:" + timeLong)
//將日期轉(zhuǎn)化為星期、獲取年月日
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("測(cè)試:星期" + weekDay+"."+year+"-"+month+"-"+monthDay)
將日期轉(zhuǎn)化為毫秒主要使用的是SimpleDateFormat.parse()。使用時(shí)需要注意的是:
使用SimpleDateFormat.parse()的時(shí)候,經(jīng)常會(huì)有ParseException發(fā)生,原因是輸入的字符串格式跟SimpleDateFormat定義的格式不一致。
這時(shí)候,可以先通過(guò)SimpleDateFormat.format把參數(shù)轉(zhuǎn)成符合格式的字符串,然后再調(diào)用SimpleDateFormat.parse()
比如:
錯(cuò)誤情況:
一、
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")”
這兩行都會(huì)報(bào)ParseException,因?yàn)榕cSimpleDateFormat的格式時(shí)間不統(tǒng)一。
正確情況:
先通過(guò)SimpleDateFormat.format把參數(shù)轉(zhuǎn)成符合格式的字符串,然后再調(diào)用SimpleDateFormat.parse()
//將日期轉(zhuǎn)化為毫秒值
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("測(cè)試:正確毫秒是" + time_date)
} catch (e: ParseException) {
OLogsProUtil.e("error")
}
本文地址:https://blog.csdn.net/NewActivity/article/details/108846204
總結(jié)
以上是生活随笔為你收集整理的android获取毫秒,Android 日期转为为毫秒,毫秒转化为日期,获取当期日期年、月、日...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android自定义图片文本,Andro
- 下一篇: 威联通装linux百度网盘,威联通NAS