convert timestamp into current date in android(在android中将时间戳转换为当前日期)
问题描述
我在显示日期时遇到问题,我得到的时间戳为 1379487711,但据此实际时间是 2013 年 9 月 18 日下午 12:31:51,但它显示的时间为 1970 年 17 月 41 日.如何显示为当前时间.
I have a problem in displaying the date,I am getting timestamp as 1379487711 but as per this the actual time is 9/18/2013 12:31:51 PM but it displays the time as 17-41-1970. How to show it as current time.
为了显示时间,我使用了以下方法:
for displaying time I have used the following method:
private String getDate(long milliSeconds) {
// Create a DateFormatter object for displaying date in specified
// format.
SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis((int) milliSeconds);
return formatter.format(calendar.getTime());
}
推荐答案
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time * 1000);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}
注意我把时间放在 setTimeInMillis 中,而不是 int,注意我的日期格式是 MM 而不是 mm(mm 是分钟,而不是月,这就是为什么你有一个月份应该是41"的值)
notice that I put the time in setTimeInMillis as long and not as int, notice my date format has MM and not mm (mm is for minutes, and not months, this is why you have a value of "41" where the months should be)
对于 Kotlin 用户:
fun getDate(timestamp: Long) :String {
val calendar = Calendar.getInstance(Locale.ENGLISH)
calendar.timeInMillis = timestamp * 1000L
val date = DateFormat.format("dd-MM-yyyy",calendar).toString()
return date
}
不要删除的评论:试图编辑这篇文章的亲爱的人 - 我认为完全改变答案的内容是违反本网站的行为规则的.今后请不要这样做.-LenaBru
COMMENT TO NOT BE REMOVED: Dear Person who tries to edit this post - completely changing the content of the answer is, I believe, against the conduct rules of this site. Please refrain from doing so in the future. -LenaBru
这篇关于在android中将时间戳转换为当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在android中将时间戳转换为当前日期
基础教程推荐
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
