java判断是否是日期

如题所述

楼主提出的问题有点片面,我的理解是,你是不是想判断字符串是不是日期格式?如果已经是日期类型,那就不需要判断了,对把。判断给定字符串是不是日期我给你提供两种解决思路,一种是用正则,代码我给你写好了。

public boolean isDate(String date) {
/**
 * 判断日期格式和范围
 */
String rexp = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";

Pattern pat = Pattern.compile(rexp);

Matcher mat = pat.matcher(date);

boolean dateType = mat.matches();

return dateType;
}

参数就是你要判断的日期字符串,返回布尔值;

另一种方式就是:玩字符串正则才是王道嘛!希望采纳

public boolean isValidDate(String str) {
boolean convertSuccess = true;
// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
//如果想判断格式为yyyy-MM-dd,需要写成-分隔符的形式
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {

format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// 如果抛出ParseException或者NullPointerException,就说明格式不对
convertSuccess = false;
}
return convertSuccess;
}

推荐使用正则,

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-03-18
public class DateUtil
{
private static final SimpleDateFormat dateFormat = null;
static
{
dateFormat = new SimpleDateFormat("yyyy/MM/dd");
dateFormat.setLenient(false);
}

public static boolean isValidDate(String s)
{
try
{
dateFormat.parse(s);
return true;
}
catch (Exception e)
{
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return false;
}
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test2
{
public static void main(String[] args)
{
String date_string="201609";
// 利用java中的SimpleDateFormat类,指定日期格式,注意yyyy,MM大小写
// 这里的日期格式要求javaAPI中有详细的描述,不清楚的话可以下载相关API查看
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");

// SimpleDateFormat format=new SimpleDateFormat("yyyyMM");
// 设置日期转化成功标识
boolean dateflag=true;
// 这里要捕获一下异常信息
try
{
Date date = format.parse(date_string);
} catch (ParseException e)
{
dateflag=false;
}finally{
// 成功:true ;失败:false
System.out.println("日期是否满足要求"+dateflag);
}
}
}
第2个回答  2014-11-06
以下代码可以判断某个字符串是否是合法的日期(格式为:yyyy/MM/dd HH:mm)

public static boolean isValidDate(String str) {
boolean convertSuccess=true;
     // 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {
     // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
convertSuccess=false;
}
return convertSuccess;
}本回答被提问者和网友采纳