2011-05-25 63 views
18

我想从时间戳中获取格式为MM/DD/YY的日期。如何从时间戳中获取MM/DD/YY格式的日期

我用下面的方法,但它并没有给出正确的输出

final Calendar cal = Calendar.getInstance(); 
cal.setTimeInMillis(Long.parseLong(1306249409));  
Log.d("Date--",""+cal.DAY_OF_MONTH);  
Log.d("Month--",""+cal.MONTH);  
Log.d("Year--",""+cal.YEAR); 

但它给出了类似下面的输出

日期 - 5月 - 2 年 - 1

正确日期为2010年5月24日时间戳 - 1306249409

注 - 时间戳由Web服务这是在我的应用程序中使用。

+1

Android有SimpleDateFormat吗? – 2011-05-25 11:13:37

+0

真的是2010年5月24日,而不是2011年? – 2011-05-25 12:30:55

回答

22

更好的办法

只需使用SimpleDateFormat

new SimpleDateFormat("MM/dd/yyyy").format(new Date(timeStampMillisInLong)); 

错误在你的方法

DAY_OF_MONTHMONTH,..等都是使用 Calendar类内部只是不断int值

您可以通过cal.get(Calendar.DATE)

+6

千万不要用小写'l'来表示这个数字是一个文字'long';总是使用大写的'L'。 'l'看起来像数字'1'。 – Jesper 2011-05-25 11:16:20

18

使用SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date date = new Date(); 
String time = sdf.format(date); 
7

什么是错度日cal表示的日期:

Calendar.DAY_OF_MONTHCalendar.MONTH等是用于访问这些特定字段的静态常量。 (他们将保持不变,无论你提供什么样的setTimeInMillis。)


如何解决它:

让那些特定领域可以使用.get(int field)-method,就像这样:

Log.d("Month--",""+cal.get(Calendar.MONTH)); 

正如其他人指出的,有更方便的格式化日志记录日期。你可以使用例如SimpleDateFormat,或者像我通常在记录时那样使用格式字符串和String.format(formatStr, Calendar.getInstance())

+0

感谢您的回复,我确实根据您的答案进行了更改,但是我获得了月 - 0,年 - 1970年和日 - 01 – 2011-05-25 11:44:50

+0

@Mohit Kanada,有些字段为0索引。 @Grzegorz Szpetkowski答案考虑到了这一点。例如'SimpleDateFormat'或'String.format'方法可能会更好。 – aioobe 2011-05-25 12:10:04

1

Java使用自1970年1月1日以来的毫秒数来表示时间。如果你计算1306249409毫秒的时间,你会发现它只有362天,所以你的假设是错误的。

此外,cal.DAY_OF_MONTH保持不变。使用cal.get(Calendar.DAY_OF_MONTH)获取月份的日期(该日期的其他部分相同)。

3
 Date date = new Date(System.currentTimeMillis()); 
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy"); 
    String s = formatter.format(date); 
    System.out.println(s); 
2
TimeZone utc = TimeZone.getTimeZone("UTC"); // avoiding local time zone overhead 
final Calendar cal = new GregorianCalendar(utc); 

// always use GregorianCalendar explicitly if you don't want be suprised with 
// Japanese Imperial Calendar or something 

cal.setTimeInMillis(1306249409L*1000); // input need to be in miliseconds 

Log.d("Date--",""+cal.get(Calendar.DAY_OF_MONTH)); 

Log.d("Month--",""+cal.get(Calendar.MONTH) + 1); // it starts from zero, add 1 

Log.d("Year--",""+cal.get(Calendar.YEAR)); 
+0

+1,很好地回答了问题。 – aioobe 2011-05-25 13:37:40

0

使用String.format这是能够转换长(毫秒)的日期/时间字符串以不同的格式:

String str; 
    long time = 1306249409 * 1000L; // milliseconds 
    str = String.format("%1$tm/%1$td/%1$ty", time); // 05/24/11 
    str = String.format("%tF", time);    // 2011-05-24 (ISO 8601) 
    str = String.format("Date--%td", time);   // Date--24 
    str = String.format("Month--%tm", time);   // Month--05 
    str = String.format("Year--%ty", time);   // Year--11 

文档:format string

相关问题