例如:"yyyy-MM-dd" 是一个有效的格式,但是,"aaaa-bb-CC" 就不是一个有效的格式,咋样用java去验证哪?我知道,用SimpleDateFormat的构造器可以验证,例如:
new SimpleDateFormat("dddddd"); 就会跑出异常,但这种办法看起来不太好,不知道大家是否还有其他更好的办法?谢谢

解决方案 »

  1.   

    api里还有
    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
      

  2.   

    Calendar 类  
    //------------------------------------------------------
    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()));  
       }  
      }  
     }  
    }  
      

  3.   

    你可以到JDK的SimpleDateFormat.java里compile(String pattern)看它是怎么验证pattern的,也许可以给你一点提示,不过明显new SimpleDateFormat("dddddd"); 出异常的判断更好一些
      

  4.   

    可以尝试将“aaaa-bb-cc”在脚本里取到,然后拆分成3个部分,用isNaN()判断这3个部分是否是数字,比如var aa="aaaa"; if(!isNaN(aa)){return true;}
      

  5.   

    en 可以用 properties文件
      

  6.   

    谢谢大家:
    看来你们还是没太理解我的意图,我是想验证格式本身是否合法,而不是日期本身,jonay还贴边,但是我看了源代码,太长了,这么一个小功能占用那么些代码,也不太合适。看来没有再好的办法了,只好用构造器来验证。