Date类的相关方法记录

1.Date类中的时间单位是毫秒,System.currentTimeMills()方法就是获取当前时间到1970年1月1日0时0分0秒(西方时间)的毫秒数。

public class Test6 {
    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
        //返回距离时间原点的毫秒数1576552904402
    }
}

2.因为中国在东八区,所以时间原点其实是1970年1月1日8时0分0秒。

3.Date date =new Date(),无参构造新建一个Date类对象时,对象值默认为当前时间。

Date date=new Date();
System.out.println(date);
//打印当前时间Tue Dec 17 11:23:52 CST 2019

4.Date date =new Date(Long time),有参构造时,传入的参数为长整型时,根据time的毫秒数计算当前的日期。

 Date date1=new Date(1576552904402L);
 System.out.println(date1);
//打印距离原点1576552904402毫秒的时间Tue Dec 17 11:21:44 CST 2019

5.Long time=date.getTime(),方法返回当前日期到时间原点的毫秒数,相当于System.currentTimeMills()方法。

Long time=date1.getTime();
System.out.println(time);
//打印date1距离原点的毫秒数1576552904402

 6.有时候我们想要获取的日期格式并不是默认的格式,则要用的DateFormat类来格式化日期,也就是将日期转换成某种格式的文本。当然,我们可以格式化日期,也就可以将文本解析成日期,这两个步骤是可逆的。因为DateFormat是一个抽象类,不能直接使用,所以我们需要用它的子类。下面以我们常用的SimpleDateFormat为例:

成员方法:String format(Date date) :按照指定的模式,把Date日期格式化为符合模式的字符串

                  Date parse(String source):把符合模式的字符串解析为Date日期

构造方法:SimpleDateFormat(String pattern) :用给定的模式和默认语言环境的日期格式符号构造SimpeDateFormat

                  参数:String pattern:传递指定的模式

                  模式:区分大小写的!!!

Y

M

D

该年中的第几日

d

该月中的第几日

H

m

s

 

public class Test6 {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("YYYY年MM月dd日HH时mm分ss秒");
        Date date=new Date();
        String d =sdf.format(date);
        System.out.println(d);  //2019年12月17日11时36分57秒
        Date date1=sdf.parse(d);
        System.out.println(date1);//Sun Dec 30 11:36:57 CST 2018
    }
}

猜你喜欢

转载自www.cnblogs.com/iceywu/p/12015285.html
今日推荐