例如:"yyyy-MM-dd" 是一个有效的格式,但是,"aaaa-bb-CC" 就不是一个有效的格式,咋样用java去验证哪?我知道,用SimpleDateFormat的构造器可以验证,例如:
new SimpleDateFormat("dddddd"); 就会跑出异常,但这种办法看起来不太好,不知道大家是否还有其他更好的办法?谢谢
new SimpleDateFormat("dddddd"); 就会跑出异常,但这种办法看起来不太好,不知道大家是否还有其他更好的办法?谢谢
调试欢乐多
ring dateTime = MessageFormat.format("{0,date,yyyy-MM-dd-HH-mm:ss:ms}" ,
new Object[] {
new java.sql.Date(System.currentTimeMillis())
});
说明: yyyy-MM-dd-HH-mm:ss:ms 年yyyy 月MM 日dd 时(大写为24进制,小写为12进制) 分mm 秒ss 微妙ms
//------------------------------------------------------
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.DateFormat; public class DateExample5
{ public static void main(String[] args)
{
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL); // Create our Gregorian Calendar.
GregorianCalendar cal = new GregorianCalendar();
// Set the date and time of our calendar
// to the system&s date and time
cal.setTime(new Date()); System.out.println("System Date: " +
dateFormat.format(cal.getTime())); // Set the day of week to FRIDAY
cal.set(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.FRIDAY);
System.out.println("After Setting Day of Week to Friday: " +
dateFormat.format(cal.getTime())); int friday13Counter = 0;
while (friday13Counter <= 10)
{ // Go to the next Friday by adding 7 days.
cal.add(GregorianCalendar.DAY_OF_MONTH, 7); // If the day of month is 13 we have
// another Friday the 13th.
if (cal.get(GregorianCalendar.DAY_OF_MONTH) == 13)
{
friday13Counter++;
System.out.println(dateFormat.format(cal.getTime()));
}
}
}
}
看来你们还是没太理解我的意图,我是想验证格式本身是否合法,而不是日期本身,jonay还贴边,但是我看了源代码,太长了,这么一个小功能占用那么些代码,也不太合适。看来没有再好的办法了,只好用构造器来验证。