我需要以指定格式驗證日期,其中兩個輸入僅在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/YYYY
where it should throw an
exception
,因爲我已經給了year as 20 and the format is 'YYYY'
,但我不給例外。
請幫我..謝謝提前
看一看這個鏈接它會省去很多麻煩http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html – Jabir
'dates = new Date();'是一個日期對象,您在'simple_format中使用它。格式(日期);'所以它不會給出任何異常,並且它正常工作。 – eatSleepCode
對不起,這是正確的代碼..更早的一個是檢查格式.. '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 }' –