Java中的Util.Date 的某些方法过时了,如何将String类型的时间转换成Util.Date 呢?
如: “2011-07-08 04:00:00” 如何类型转换成Date类型呢(值不变还是 2011-07-08 04:00:00)??
还有就是如何从String类型的时间得到该时间距 1970-01-01 00:00:00.000 的毫秒数???郁闷呀!!

解决方案 »

  1.   


    String s = "2011-07-08 04:00:00";
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date d = df.parse(s);
    Long time = d.getTime();
      

  2.   

    java中日期类型与字符串相互转换由于经常用到日期类型和字符串类型的相互转换,这里总结一下,希望能给大家有帮助。//DateTest.java
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.text.ParseException;public class DateTest{
       
       //JDK中的日期格式(年-月-日)
       public final static String jdkDateFormat = "yyyy-MM-dd";
           
       //JDK中的日期时间格式(年-月-日 时:分:秒)
       public final static String jdkDateTimeFormat = "yyyy-MM-dd HH:mm:ss";
       
       //字符串转换为日期
       public static Date strToDate(String strDate){
           SimpleDateFormat dateFormat = new SimpleDateFormat(jdkDateFormat);
           Date date = null;
           try{
          date = dateFormat.parse(strDate);
        }catch(ParseException e){
           System.out.println(e.getMessage());
        }
        return date;
       }   //字符串转换为日期时间
    public static Date strToDateTime(String strDateTime){
           SimpleDateFormat dateTimeFormat = new SimpleDateFormat(jdkDateTimeFormat);
        Date dateTime = null;
        try{
          dateTime = dateTimeFormat.parse(strDateTime);
        }catch(ParseException e){
           System.out.println(e.getMessage());
        }
        return dateTime;
       }
       
       //日期转换为字符串
       public static String dateToStr(Date date){
           SimpleDateFormat dateFormat = new SimpleDateFormat(jdkDateFormat); 
        String strDate = dateFormat.format(date);
        return strDate;
       }
       
       //日期时间转换为字符串
       public static String dateTimeToStr(Date date){
           SimpleDateFormat dateTimeFormat = new SimpleDateFormat(jdkDateTimeFormat); 
        String strDateTime = dateTimeFormat.format(date);
        return strDateTime;
       }
           
       public static void main(String[] args){
        
        //字符串转换为日期
        String strDate = new String("2007-08-19");
        String strDateTime = new String("2007-08-19 16:38:17");
        Date date = strToDate(strDate);
        Date dateTime = strToDateTime(strDateTime);    //日期转换为字符串
        String strDate2 = dateToStr(date);
        String srtDate3 = dateToStr(dateTime);
        String strDateTime2 = dateTimeToStr(date);
        String srtDateTime3 = dateTimeToStr(dateTime);
       
        System.out.println(strDate2);
        System.out.println(srtDate3);
        System.out.println(strDateTime2);
        System.out.println(srtDateTime3);
       }
    }