现在的位置: 首页 > 综合 > 正文

字符串“1990-8”,“1990.8”,“1990-8-8”,“1990.8.8”四种情况串转Date

2013年01月11日 ⁄ 综合 ⁄ 共 1965字 ⁄ 字号 评论关闭
    /****
     * 日期String串转Date
     * @param str
     * @return
     */
    
    public static  Date parseDate(String str){
        Date d = new Date();
        String oper = str;
        if(oper.indexOf('.')!=-1){
            int count = 0;
            while(oper.indexOf('.')!=-1){
                count++;
                oper = oper.substring(oper.indexOf('.')+1);
                
            }
            if(count ==1){
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
                 try {
                     d = sdf.parse(str);
                    System.out.println(sdf.format(d));
                    
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        
            
            if(count==2){
                
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
             try {
                 d = sdf.parse(str);
                System.out.println(sdf.format(d));
                
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
            
            
        }
        if(str.indexOf('-')!=-1){
            
            int count = 0;
            while(oper.indexOf('-')!=-1){
                count++;
                oper = oper.substring(oper.indexOf('-')+1);
                
            }
            if(count ==1){
                
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                 try {
                     d = sdf.parse(str);
                    System.out.println(sdf.format(d));
                    
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        
            
            if(count==2){
                
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
             try {
                 d = sdf.parse(str);
                System.out.println(sdf.format(d));
                
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
            
        }
        
        return d;
    }
【上篇】
【下篇】

抱歉!评论已关闭.