2012-01-07 20 views
0
//get current date 
SimpleDateFormat monthFormat = new SimpleDateFormat("M"); 
int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis()))); 

SimpleDateFormat yearFormat = new SimpleDateFormat("YYYY"); 
int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis()))); 

我試圖建立一個日曆視圖,並且我開始檢索當前年份和月份。然而,返回的是一個字符串,而我想要一個int在數組中使用等。BlackBerry:正在檢索當前的年月日

上面的代碼給了我一個錯誤,最有可能是由於Integer.parseInt函數。

我不能使用它嗎?什麼是檢索年,月和日的最佳方式。

回答

0
SimpleDateFormat monthFormat = new SimpleDateFormat("MM"); 
int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis()))); 

SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); 
int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis()))); 

將「M」更改爲「MM」和「YYYY」爲「yyyy」。

0

它確實有用!我必須使用yyyy而不是YYYY。黑莓文檔將其作爲YYYY

1

您可以使用壓延類來獲得時間

這是默認的日期是指當前日期:

Calendar cal=Calendar.getInstance(); 
     System.out.println("YEAR:"+cal.get(Calendar.YEAR)+" MONTH: "+cal.get(Calendar.MONTH)+1+" DAY: "+cal.get(Calendar.DAY_OF_MONTH)); 
     //out put as YEAR:2012 MONTH: 01 DAY: 7 

這是指定日期:

Date date1=new Date(Long.parseLong("13259152444455"));//or Date date1=new Date(13259152444455L); 
      cal=Calendar.getInstance(); 
      cal.setTime(date1); 
      System.out.println("YEAR:"+cal.get(Calendar.YEAR)+" MONTH: "+cal.get(Calendar.MONTH)+1+" DAY: "+cal.get(Calendar.DAY_OF_MONTH)); 
    //  output as YEAR:2390 MONTH: 21 DAY: 2 
+0

你並不需要使用'Long.parseLong()'將大的文字傳遞給'Date()'構造函數。在整數字面上使用'L'後綴,例如:'new Date(13259152444455L);' – 2012-01-09 22:18:39

+0

謝謝,我會改變 – 2012-01-10 04:12:16

相關問題