Java 在android中将时间戳转换为当前日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18929929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert timestamp into current date in android
提问by jkk
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.
我在显示日期时遇到问题,我得到的时间戳为 1379487711,但根据此实际时间是 9/18/2013 12:31:51 PM,但它显示的时间为 17-41-1970。如何将其显示为当前时间。
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());
}
采纳答案by Lena Bru
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;
}
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)
请注意,我将时间放在 setTimeInMillis 中,而不是 int,请注意我的日期格式有 MM 而不是 mm(mm 是分钟,而不是月,这就是为什么你有一个值“41”的月份应该是)
***for kotlin users:
*** 对于 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
}
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
不可删除的评论: 亲爱的试图编辑这篇文章的人- 我相信,完全改变答案的内容违反了本网站的行为规则。以后请不要这样做。-LenaBru
回答by kyogs
convert timestamp into current date:
将时间戳转换为当前日期:
private Date getDate(long time) {
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();//get your local time zone.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
sdf.setTimeZone(tz);//set time zone.
String localTime = sdf.format(new Date(time) * 1000));
Date date = new Date();
try {
date = sdf.parse(localTime);//get local date
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
回答by Kaushik
For converting time stamp to current time
用于将时间戳转换为当前时间
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
java.util.Date currenTimeZone=new java.util.Date((long)1379487711*1000);
Toast.makeText(TimeStampChkActivity.this, sdf.format(currenTimeZone), Toast.LENGTH_SHORT).show();
回答by sivi
DateFormat df = new SimpleDateFormat("HH:mm", Locale.US);
final String time_chat_s = df.format(time_stamp_value);
The time_stamp_value variable type is long
time_stamp_value 变量类型很长
With your code it will look something like so:
使用您的代码,它看起来像这样:
private String getDate(long time_stamp_server) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
return formatter.format(time_stamp_server);
}
I change "milliseconds" to time_stamp_server. Consider changing the name of millisecond to "c" or to something more global. "c" is really good because it relates to time and to computing in much more global way than milliseconds does. So, you do not necessarily need a calendar object to convert and it should be as simple as that.
我将“毫秒”更改为 time_stamp_server。考虑将毫秒的名称更改为“c”或更全局的名称。“c”真的很好,因为它与时间和计算有关,而不是毫秒。因此,您不一定需要一个日历对象来转换,它应该就这么简单。
回答by Vinod Makode
If you want show chat message look like what up app, then use below method. date format you want change according to your requirement.
如果你想显示聊天消息看起来像什么应用程序,然后使用下面的方法。您想要根据您的要求更改的日期格式。
public String DateFunction(long timestamp, boolean isToday)
{
String sDate="";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar c = Calendar.getInstance();
Date netDate = null;
try {
netDate = (new Date(timestamp));
sdf.format(netDate);
sDate = sdf.format(netDate);
String currentDateTimeString = sdf.format(c.getTime());
c.add(Calendar.DATE, -1);
String yesterdayDateTimeString = sdf.format(c.getTime());
if(currentDateTimeString.equals(sDate) && isToday) {
sDate = "Today";
} else if(yesterdayDateTimeString.equals(sDate) && isToday) {
sDate = "Yesterday";
}
} catch (Exception e) {
System.err.println("There's an error in the Date!");
}
return sDate;
}
回答by Basil Bourque
tl;dr
tl;博士
You have a number of whole secondssince 1970-01-01T00:00:00Z
rather than milliseconds.
你有许多的整秒,因为1970-01-01T00:00:00Z
不是毫秒。
Instant
.ofEpochSecond( 1_379_487_711L )
.atZone(
ZoneId.of( "Africa/Tunis" )
)
.toLocalDate()
.format(
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
2013-09-18T07:01:51Z
2013-09-18T07:01:51Z
Whole seconds versus Milliseconds
整秒与毫秒
As stated above, you confused a count-of-seconds with a count-of-milliseconds.
如上所述,您将秒数与毫秒数混淆了。
Using java.time
使用 java.time
The other Answers may be correct but are outdated. The troublesome old date-time classes used there are now legacy, supplanted by the java.time classes. For Android, see the last bullets below.
其他答案可能是正确的,但已过时。那里使用的麻烦的旧日期时间类现在是遗留的,被 java.time 类取代。对于 Android,请参阅下面的最后一个要点。
The Instant
class represents a moment on the timeline in UTCwith a resolution of nanoseconds(up to nine (9) digits of a decimal fraction).
该Instant
级表示时间轴上的时刻UTC,分辨率为纳秒(最多小数的9个位数)。
Instant instant = Instant.ofEpochSecond( 1_379_487_711L ) ;
instant.toString(): 2013-09-18T07:01:51Z
Instant.toString(): 2013-09-18T07:01:51Z
Apply the time zone through which you want to view this moment.
应用您想要查看这一时刻的时区。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2013-09-18T03:01:51-04:00[America/Montreal]
zdt.toString(): 2013-09-18T03:01:51-04:00[美国/蒙特利尔]
Generate a string representing this value in your desired format.
以您想要的格式生成一个表示此值的字符串。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = zdt.format( f ) ;
18-09-2013
18-09-2013
See this code run live at IdeOne.com.
About java.time
关于 java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABPproject adapts ThreeTen-Backport(mentioned above) for Android specifically.
- See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 所述ThreeTenABP项目适应ThreeTen-反向移植(上述)为Android特异性。
- 请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by Paras Andani
If your result always returns 1970, try this way :
如果您的结果总是返回 1970,请尝试以下方法:
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(timestamp * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();
You need to multiple your TS value by 1000
您需要将 TS 值乘以 1000
It's so easy to use it.
使用它是如此容易。
回答by ekashking
I got this from here: http://www.java2s.com/Code/Android/Date-Type/CreateDatefromtimestamp.htm
我从这里得到这个:http: //www.java2s.com/Code/Android/Date-Type/CreateDatefromtimestamp.htm
None of the above answers worked for me.
以上答案都不适合我。
Calendar c = Calendar.getInstance();
c.setTimeInMillis(Integer.parseInt(tripBookedTime) * 1000L);
Date d = c.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
return sdf.format(d);
And by the way: ("dd-MM-yyyy", cal)
is not recognized by Android - "Cannot resolve method".
顺便说一句:("dd-MM-yyyy", cal)
Android 无法识别 - “无法解析方法”。