关于的Java日期时间函数

package test;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class SQLDate {

    public static void main(String[] args){
        
        System.out.println(System.currentTimeMillis());        //结果:1244711626453
        
        java.util.Date date1 = new java.util.Date();
        System.out.println(date1.toString());    //结果: Thu Jun 11 16:27:57 CST 2009
        
        //java.sql.Date extends java.util.Date
        java.sql.Date date2 = new java.sql.Date(System.currentTimeMillis());
        System.out.println(date2.toString());    //结果: 2009-06-11
        
        java.sql.Date date3 = new java.sql.Date(date1.getTime());
        System.out.println(date3.toString());    //结果:2009-06-11
        
        //Timestamp extends java.util.Date
        Timestamp stamp1 = new Timestamp(System.currentTimeMillis());
        System.out.println(stamp1.toString());    //结果: 2009-06-11 16:27:57.75
        
        Timestamp stamp2 = new Timestamp(date1.getTime());
        System.out.println(stamp2.toString());    //结果:2009-06-11 16:52:56.171

        //日期时间转换成格式化的字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        //format(java.util.Date date), Timestamp是java.util.Date的子类
        String timeStr =  sdf.format(stamp1);    
        System.out.println(timeStr);    //结果:2009/06/11 16:52:56
        
        //SimpleDateFormat extends DateFormat,DateFormat是抽象类
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String timeStr2 = df.format(date1);
        String timeStr3 = df.format(date2);
        System.out.println(timeStr2);    //结果:2009/06/11 16:52:56
        System.out.println(timeStr3);    //结果: 2009/06/11 16:52:56
        
        //字符串转化为日期时间
        try {
            //parse()中的参数必须与sdf中定义的格式一致,否则抛异常
            java.util.Date date6 = sdf.parse("2009/12/10 5:12:02");
            System.out.println(date6.toString()); //结果: Thu Dec 10 05:12:02 CST 2009
            
            java.sql.Date date7 = new java.sql.Date(date6.getTime());
            System.out.println(date7.toString()); //结果: 2009-12-10
            
            //注意: sdf.parse()返回值是java.util.Date类型,不能转化成java.sql.Date类型
            //java.sql.Date date8 = (java.sql.Date)sdf.parse("2009/12/10 5:12:02"); //不可行
            
            Timestamp stamp9 = new Timestamp(date7.getTime());
            System.out.println(stamp9.toString()); //结果: 2009-12-10 05:12:02.0
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
    }
}
 

你可能感兴趣的:(java,sql)