2013-08-02 96 views
0

在下面的代碼 輸入:爪哇日期轉換

Enter Date: 3/2/2011 

輸出:

Entered Date is February 3, 2011 
Entered Month is 02 

問題是,當我輸入這個日期3/14/2012,日期格式功能自動更改一個月12+22月)。如果我輸入13/15/2011,它會將月份更改爲3(12+3)

應該在14「無效月」

package lesson4; 

import java.util.*; 

import java.text.*; 
public class ConvertDate { 
static String Month; 
static String fulldate; 
static int month; 
static int[] montharray={1,2,3,4,5,6,7,8,9,10,11,12}; 
public static void main(String[] args){ 


Scanner sc = new Scanner(System.in); 
System.out.print("Enter Date: "); 
String ind = sc.nextLine(); 
//Date now = new Date(); 
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
SimpleDateFormat f = new SimpleDateFormat("dd"); 
SimpleDateFormat m = new SimpleDateFormat("MM"); 

Date d = null; 
    Date e=null; 
Date g=null; 


try { 
d=df.parse(ind); 
e=df.parse(ind); 
g=df.parse(ind); 
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG); 


fulldate = df3.format(d); 
Month=m.format(g); 
month =Integer.parseInt(Month); 

String date =f.format(e); 
} catch (ParseException e1) { 
// TODO Auto-generated catch block 



e1.printStackTrace(); 
} 





System.out.println("The entered date is: " + fulldate); 
System.out.println("The entered month is: " + Month); 

} 
} 
+0

兄弟你能舉個例子..我會很棒 –

+0

@Nizil。不,它不會。 DateFormat是執行此操作的正確方法。 –

+0

@RohitJain我同意,'DateFormat'比字符串解析好得多,但忘了'setLenien(bool)',在發佈你的答案之前沒有看到另一個解決方案;) – NiziL

回答

4

對於每個DateFormat實例,你需要調用setLenient虛假的說法:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
df.setLenient(false); 
DateFormat f = new SimpleDateFormat("dd"); 
f.setLenient(false); 
DateFormat m = new SimpleDateFormat("MM"); 
m.setLenient(false); 

DateFormat#setLenient(boolean)文檔:

隨着寬鬆的解析,解析器可以使用啓發式來解釋不精確的輸入這個對象的格式。通過嚴格的解析,輸入必須匹配這個對象的格式。

+0

偉大的Rohit ..但我可以想要從數組中檢查月份..我限制使用數組,如果我在月中輸入14,那麼它應該顯示無效的月份....你的代碼只是捕捉異常 –

+0

@JamesBlent。您可以捕獲異常,並顯示您自己的消息。你可以搜索一些很好的異常處理教程。 –

+0

是的,我有緩存異常,「無效日期」..但我怎麼能給出錯誤使用數組..我已經聲明數組中的代碼...請幫助 –

2

參考給出錯誤這些格式Java Date Format Docs:在第二位,而

Formats for datetime

DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 

你期待月輸入首先放置它。

嘗試:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); 
0

您是否嘗試過在您的DateFormat上使用「setLenient(false)」來強制DateFormat嚴格分析輸入? 我還沒有嘗試過,但最近偶然發現了這個功能。