繁体   English   中英

如何从Timestamp获取MM / DD / YY格式的日期

[英]How can I get Date in MM/DD/YY format from Timestamp

我想从时间戳中获取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日的Timestamp - 1306249409

注 - 时间戳由我的应用程序中使用的Web服务接收。

更好的方法

只需使用SimpleDateFormat

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

你的方法中的错误

DAY_OF_MONTHMONTH ,..等只是Calendar类在内部使用的常量int值

您可以通过cal.get(Calendar.DATE)获取cal表示的日期

使用SimpleDateFormat

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

怎么了:

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


如何解决:

要获取这些特定字段,您可以使用.get(int field) -method ,如下所示:

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

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

        Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
    String s = formatter.format(date);
    System.out.println(s);
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));

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

而且, cal.DAY_OF_MONTH保持不变。 使用cal.get(Calendar.DAY_OF_MONTH)获取月中的某一天(与日期的其他部分相同)。

使用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

文档: 格式字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM