欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java检查字符串是否是合法的日期,java检查字符串日期,下面例子使用Simple

来源: javaer 分享于  点击 17504 次 点评:105

java检查字符串是否是合法的日期,java检查字符串日期,下面例子使用Simple


下面例子使用SimpleDateFormat类的parse方法尝试解析字符串,若解析成功则说明字符串是合法的日期字符串,否则则说明输入的字符串不是合法的日期。

import java.text.SimpleDateFormat;import java.text.ParseException;public class DateTest {  public boolean isValidDate(String inDate) {    if (inDate == null)      return false;    //set the format to use as a constructor argument    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    if (inDate.trim().length() != dateFormat.toPattern().length())      return false;    dateFormat.setLenient(false);    try {      //parse the inDate parameter      dateFormat.parse(inDate.trim());    }    catch (ParseException pe) {      return false;    }    return true;  }  public static void main(String[] args) {    DateTest test = new DateTest();    System.out.println(test.isValidDate("2004-02-29"));    System.out.println(test.isValidDate("2005-02-29"));  }}

输出如下:

truefalse
相关栏目:

用户点评