2012-04-20 101 views
0

我想respresented因爲這 「週四1月1八點40分38秒GMT + 01:00 1754」 時時間特定格式的Android的Java

,所以我這樣做:

   Date datu = new Date(); 
       datu.setYear(1754); 
       datu.setMonth(0); 
       datu.setDate(1); 
       DateFormat.format("%tc", datu); 

       // DATU = Thu Jan 01 08:40:38 GMT+01:00 3654 
       String startTime = datu.toGMTString(); 

現在問題是我在代碼中設置了1754年。但當我打印出來。有3654?

編輯: datu.setYear(1754-1900)可以做到這一點。但不是有另一種方式嗎?

回答

1

請嘗試這樣的:

SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd hh:mm:ss 'GMT'Z yyyy"); 
Calendar c = Calendar.getInstance(); 
c.set(Calendar.YEAR,1754); 
c.set(Calendar.MONTH, 0); // JAN 
c.set(Calendar.DATE, 1); 
System.out.println(sdf.format(new Date(c.getTimeInMillis()))); 

輸出

Tue Jan 01 05:23:55 GMT+0800 1754 
0

看來那個日期.SetYear是deprecated。根據文檔,您應該使用Calendar.set(Calendar.YEAR,year)來代替。

0

正如你所說,date.setYear(希望年1900年)解決了這個問題。值得注意的是,該方法已棄用,因此使用Calendar類並不需要從年份中減去1900。代碼段將實現您正在使用的日曆做的是下面給:

Calendar calendar =Calendar.getInstance(); 
calendar.setTime(date);// note that the date object here will be datu according to 
//your code. It could be any object of the Date class 
int year = calendar.get(Calendar.YEAR); 

希望這有助於。

隨時標記爲答案,如果它解決您的問題。 祝你好運!

1

您使用的是什麼版本的Java API? 我建議你改用java.text.SimpleDateFormat和java.util.Calendar。 你的代碼會是這個樣子:

Calendar cal = Calendar.getInstance(); 
cal.set(1754, 0, 1); 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // <- customize your format 
sdf.format(cal.getTime()); // <- get your string 

的date.toGMTString()方法也已經過時,所以最好避免。

+0

你會發現這裏所有的格式設置模式的元素[鏈接](http://docs.oracle.com/javase/6 /docs/api/java/text/SimpleDateFormat.html) – Kaupo 2012-04-20 08:30:56