如何将currentTimeMillis转换为可读的日期格式?(复制)

时间:2022-05-07 15:31:00

This question already has an answer here:

这个问题已经有了答案:

I want to use currentTimeMillis twice so I can calculate a duration but I also want to display Time and Date in user readable format. I'm having trouble as currentTimeMillis is good for the calculation but I can't see a built in function to convert to nice time or time/date.

我想要使用currentTimeMillis两次,这样我可以计算一个持续时间,但是我也想用用户可读的格式显示时间和日期。我遇到了麻烦,因为currentTimeMillis对计算很好,但是我看不到一个内置函数可以转换成好时间或时间/日期。

I use

我使用

android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd kk:mm:ss", new java.util.Date());

for producing nice time and date and what I'd ultimately like to do is show my resulting currentTimeMillis value into the android.text.format.DateFormat df = new android.text.format.DateFormat();

为了生成漂亮的时间和日期,我最终想要做的是将产生的currentTimeMillis值显示到android.text.format中。DateFormat df =新的android.text.format.DateFormat();

e.g.

如。

android.text.format.DateFormat df = currentTimeMillis();

when I try I get

当我尝试的时候

Type mismatch: cannot convert from long to DateFormat

类型不匹配:不能从long转换为DateFormat

I've tried to use some casting but can't see how to accomplish this.

我试过使用一些施法,但是我不知道该怎么做。

2 个解决方案

#1


111  

It will work.

它将工作。

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

#2


31  

There is a simpler way in Android

Android有一个更简单的方法

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

此外,不赞成使用Date,所以使用DateFormat类。

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

以上三行将给出:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

#1


111  

It will work.

它将工作。

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

#2


31  

There is a simpler way in Android

Android有一个更简单的方法

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

此外,不赞成使用Date,所以使用DateFormat类。

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

以上三行将给出:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM