[英]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_MONTH
, MONTH
,..等只是Calendar
類在內部使用的常量int值
您可以通過cal.get(Calendar.DATE)
獲取cal
表示的日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String time = sdf.format(date);
怎么了:
Calendar.DAY_OF_MONTH
, Calendar.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.