2014-03-04 30 views
0

我需要以指定格式驗證日期,其中兩個輸入僅在JTextfield的運行時中給出,並且將動態更改。下面是我曾嘗試代碼:指定格式的Jtextfield中的日期驗證

Date dd = new Date(); 
    DateFormat df = new SimpleDateFormat(Date_format_text.getText()); 
    try { 

     df.setLenient(false); 
     Date d1 = df.parse(Lower_date_text.getText()); 
     System.out.println("Correct"); 
     validator_LD.setVisible(false); 

    } catch (ParseException p) { 

     validator_LD.setText("*Not in mentioned Format '" + df.format(dd) + "'"); 
     validator_LD.setVisible(true); 

     System.out.println("Wrong"); 

    } 

以上是..我得到指定的日期和從文本字段中指定的格式,並嘗試根據指定的格式解析。如果不匹配,則會拋出異常。

但這不是正確在某些情況下工作:

  • 如果我給了Date 02/01/20'Format - dd/MM/YYYYwhere it should throw anexception,因爲我已經給了year as 20 and the format is 'YYYY',但我不給例外。

請幫我..謝謝提前

+0

看一看這個鏈接它會省去很多麻煩http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html – Jabir

+1

'dates = new Date();'是一個日期對象,您在'simple_format中使用它。格式(日期);'所以它不會給出任何異常,並且它正常工作。 – eatSleepCode

+0

對不起,這是正確的代碼..更早的一個是檢查格式.. 'DateFormat df = new SimpleDateFormat(Date_format_text.getText()); df.setLenient(false); 日期d1 = df.parse(Lower_date_text.getText());' //上述..我試圖解析文本到日期,所以它不會以指定的格式它會gv異常,但它的確適用於一個目的,如我在問題中提到的 'validator_LD.setVisible(false); (「Wrong」);}};}};}}}} catch(ParseException p){ } catch(ParseException p){ System.out.println }' –

回答

2

首先,你可能想看看How to Use the Focus Subsystem,注重Validating Input這可能會有幫助。

其次,由@eatSleepCode指出的那樣,您實際上並不解析字段的文本,而是簡單地格式化現有Date,所以它永遠不會拋出異常......

simple_format = new SimpleDateFormat(Date_format_text.getText()); 
// This is simply formatting the dates... 
String ss = simple_format.format(dates); 

相反,你需要使用更多的東西一樣......

String test = "02/01/20"; 
String format = "dd/MM/yyyy"; 
SimpleDateFormat sdf = new SimpleDateFormat(format); 
sdf.setLenient(false); 
try { 
    Date date = sdf.parse(test); 
    if (!sdf.format(date).equals(test)) { 
     throw new ParseException(test + " is not a valid format for " + format, 0); 
    } 
} catch (ParseException ex) { 
    ex.printStackTrace(); 
} 

這裏做的事情,是測試的格式化的語法分析器功能,而且還檢查反對什麼,所得解析Date將被格式化,如果這些輸入d不匹配它會拋出一個ParseException。這是我已經能夠得到嚴格的解析器關閉...

此外,YYYY用來表示一年,而不是一年的一週...

+1

請參閱此相關的[示例](http://stackoverflow.com/a/2241997/230513)。 – trashgod

+0

@MadProgrammer感謝兄弟,我真的是個瘋子人;) –