如何判断一个日期字符串是否合法
答案:2 悬赏:70 手机版
解决时间 2021-02-22 09:20
- 提问者网友:心牵心
- 2021-02-21 12:50
如何判断一个日期字符串是否合法
最佳答案
- 五星知识达人网友:雪起风沙痕
- 2021-02-21 12:58
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;
}
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;
}
全部回答
- 1楼网友:往事隔山水
- 2021-02-21 13:58
java为了支持多语言,没有固定的日期格式。你需要根据自己的需要指定日期格式,然后用dateformat类或者simpledateformat类来判断是否是正确的日期格式。下面的例子供参考。更详细的内容(比如yyyy,mm,dd各代表什么)可以参考javadoc。
public class dateutil
{
private static final simpledateformat dateformat = null;
static
{
// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/mm/dd区分大小写;
dateformat = new simpledateformat("yyyy/mm/dd");
// 设置lenient为false. 否则simpledateformat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
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;
}
}
// 下面这个方法则可以将一个日期按照你指定的格式输出
public static string formatdate(date d)
{
return dateformat.format(d);
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯