java的Date类和TimeStamp类

Java API中有两个Date类,一个是java.util.Date,其构造方法如下:

Date()

Date(long date)

主要方法有:

boolean after(Date when)

boolean before(Date when)

Object clone()

int compareTo(Date anotherDate)

boolean equals(Object obj)

long getTime()

String toString()

另一个是java.sql.Date,其构造方法如下:

Date(long date)

主要方法有:

int getHours()

int getMinutes()

int getSeconds()

void setHours(int i)

void setMinutes(int i)

void setSeconds(int i)

void setTime(long date)

String toString()

static Date valueOf(String s)

以下是时间和字符串之间的转化,以及时间戳获取

public class time {

    public static void main(String[] args) throws ParseException {
        // TODO Auto-generated method stub

        String stringDate="1996-06-25 12:23:26";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date birthday=sdf.parse(stringDate);
        System.out.println("把"1996-06-25 12:23:26"字符串转化为时间格式:"+birthday);
        Date timeNow=new Date();
        String timeNowFormatter=sdf.format(timeNow);
        System.out.println("把当前时间用:"yyyy-MM-dd HH:mm:ss"格式输出:"+timeNowFormatter);
        //通过格林时间设置为自己想要设置的时间,格林时间月份从0开始
        Calendar birth=Calendar.getInstance();
        birth.set(1996,05,25);
        Date birthday2=birth.getTime();
        System.out.println("通过格林时间设置某一特定时间:"+birthday2);
        Timestamp ts=new Timestamp(new Date().getTime());
        System.out.println("获得当前时间的时间戳:"+ts);
    }

}

输出结果:

把"1996-06-25 12:23:26"字符串转化为时间格式:Tue Jun 25 12:23:26 CST 1996
把当前时间用:"yyyy-MM-dd HH:mm:ss"格式输出:2016-06-28 16:35:02
通过格林时间设置某一特定时间:Tue Jun 25 16:35:02 CST 1996
获得当前时间的时间戳:2016-06-28 16:35:02.472