在java构造函数中提取日期
我需要从接收字符串变量的构造函数中验证日期mm/dd。我试过好几种方法,但都没有成功。我最后一次尝试是将字符串转换为ascii并进行验证,但也不起作用:在java构造函数中提取日期,java,constructor,Java,Constructor,我需要从接收字符串变量的构造函数中验证日期mm/dd。我试过好几种方法,但都没有成功。我最后一次尝试是将字符串转换为ascii并进行验证,但也不起作用: public Dated(String dateStr) { this.dateStr = dateStr; for (int i = 0; i < dateStr.length(); i++) { char c = dateStr.charAt(i); asciiValues = (int) c; // chan
public Dated(String dateStr)
{
this.dateStr = dateStr;
for (int i = 0; i < dateStr.length(); i++)
{
char c = dateStr.charAt(i);
asciiValues = (int) c; // change each string character to ASCII value
}
}
public void display()
{
System.out.println(asciiValues);
}
public Dated(字符串dateStr)
{
this.dateStr=dateStr;
对于(int i=0;i
据我所知,您在解析字符串值时遇到了麻烦。对
在java中,我们有很多工具可以用来验证这些东西
我将使用SimpleDateFormat
实用程序类来验证日期,并将date
转换为String
public class Dated{
private SimpleDateFormat sdf = new SimpleDateFormat("MM/dd") // M --> Month; d--> Day
public Dated(String dateStr) throws Exception{
try{
Date d = sdf.parse(dateStr);
System.out.println( d );
} catch (ParseException e) {
// you can throw that exception just to
// avoid creating the object of this class
throw e;
}
}
}
但请记住,您并不是在验证@JB Nizet
中提到的闰年日期。
你也可以通过确认年份来克服这一点
在上述代码中,如果您通过“02/29”,您将获得3月1日的日期。这不是正确的日期,因为1970年不是闰年
因此,我也会在日期验证中包含年份
要添加年份,您可以更改SimpleDateFormat,如下所示
private SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); // y --> Year
mm/dd
或哪一年?如何处理闰年?最好从构造函数中抛出ParseException,不要使用try/catch。是的,这取决于您希望类构造函数的行为方式。我加了一句try/catch,好让他有个好主意。