日期:2014-05-20  浏览次数:20737 次

JAVA 字符串格式化
例如有文本文件111.txt里的内容是
20060603
20070503
20080208

现在要把它格式化成

2006-06-03
2007-05-03
2008-02-08


新手,请多指教,高手帮忙哦~~~~~~

------解决方案--------------------
这个简单,要么使用日期格式化方法。要么简单一点,直接使用字符串处理。

str.substring(0,4)+"-"+str.substring(4,6)+"-"+str.substring(6)
------解决方案--------------------
String str =20060607
str = str.substring(0,4)+"-"+str.substring(5,6)+"-"+str.substring(7,8)
------解决方案--------------------
Java code

String str =fdsaf2006060743242 
Pattern p = Pattern.compile("[1-2][0-9]{3}[0-1][0-9][0-3][0-9]?", Pattern.CASE_INSENSITIVE);
 Matcher m = p.matcher(ss);
 while (m.find()) {
  String s = m.group();
  String y = s.substring(0, 4);
  String mon = s.substring(4, 6);
  String date = s.substring(6, 8);
  s = y + "-" + mon + "-" + date;
        }
    }

------解决方案--------------------
Java code

    public static String formatDateStr(String src)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String ret = "";
        
        try
        {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(format.parse(src.trim()));
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            ret = year + "-" + (month < 10? "0" + month: month) + "-" + (day < 10? "0" + day: day);
        }
        catch(ParseException e)
        {
            e.printStackTrace();
        }
        
        return ret;
    }

------解决方案--------------------
探讨
引用:
Java codepublicstaticvoidmain(String[] args) {
System.out.println(formatString("20060603"));
System.out.println(formatString("20070503"));
System.out.println(formatString("20080208"));
}publicstaticString formatString(String value) {returnvalue.replaceAll("(? <=[1-9])0(?!0)","-0");
}

如果是20080412,20081101,20081111,