Android 日期转为为毫秒,毫秒转化为日期,获取当期日期年、月、日
- 作者: 柏林小姐
- 来源: 51数据库
- 2021-08-28
//将时间毫秒值转化为年月日
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")
}
?
?
?
推荐阅读
热点文章
android中Bitmap用法(显示,保存,缩放,旋转)实例分析
12
android 仿微信聊天气泡效果实现思路
1
Android的尺度,drawable-xxxxxxx
2
Codeforces Round #656 (Div. 3) (C、D题)
1
Android之handler异步消息处理机制解析
6
GridView中图片显示出现上下间距过大,左右图片显示类似瀑布流的问题
0
AsyncTask的简单使用
5
两个简单Fragment之间的通信(三种方式)
18
uboot修改设置boot参数命令
41
android中实现从相册中一次性获取多张图片与拍照,并将选中的图片显示出来
2
