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

String 转换 date
这样就能转换
Java code

String nowTime="2008-01-18";
Date date = java.sql.Date.valueOf(nowTime);
System.out.println(date);



但是,带上时间就不行
Java code

String nowTime="2008-01-18 09:10:10";
Date date = java.sql.Date.valueOf(nowTime);
System.out.println(date);



怎么把String nowTime="2008-01-18 09:10:10";带时间也转换成date类型??
转换为这样格式的SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


------解决方案--------------------
String nowTime="2008-01-18 09:10:10";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date day = df.parse(nowTime);


------解决方案--------------------
java.sql.Date的概念只有年月日
看java.sql.Date.valueOf(String)的原码
Java code
    public static Date valueOf(String s) {
        int year;
        int month;
        int day;
        int firstDash;
        int secondDash;

        if (s == null)
            throw new java.lang.IllegalArgumentException();

        firstDash = s.indexOf('-');
        secondDash = s.indexOf('-', firstDash + 1);
        if ((firstDash > 0) & (secondDash > 0) & (secondDash < s.length() - 1)) {
            year = Integer.parseInt(s.substring(0, firstDash)) - 1900;
            month = Integer.parseInt(s.substring(firstDash + 1, secondDash)) - 1;
            day = Integer.parseInt(s.substring(secondDash + 1));
        } else {
            throw new java.lang.IllegalArgumentException();
        }

        return new Date(year, month, day);
    }