20-Date+Format+DateFormat+SimpleDateFormat+Calendar

一、java.util.Date

1、年:y,月:0-11,日:1-31,时:0-23,分:0-59,秒:0-61(值60和61只对闰秒发生)

注:只有日是1-xx,其他都是0-xx

2、构造函数

(1)Date():分配Date对象并初始化此对象,以表示分配它的时间--当前时间(精确到毫秒) -- 常用

(2)Date(long date)分配Date对象并初始化此对象,以表示自从标准基准时间(1970年1月1日 00:00:00 GMT)以来的指定毫秒数

        long time = System.currentTimeMillis();    //获取当前时间的毫秒值
        System.out.println(time);   //1527400740144
        Date date = new Date();
        System.out.println(date.toString());    //Sun May 27 13:59:00 CST 2018
        //等效于 Date date2 = new Date(1527400740144L);
        Date date2 = new Date(time);
        System.out.println(date2.toString());   //Sun May 27 13:59:00 CST 2018

3、方法

(1)long getTime():返回自 1970年1月1日 00:00:00 GMT 以来此Date对象表示的毫秒值

(2)void setTime(long time):设置此Date对象,以表示 1970年1月1日 00:00:00 GMT 以后time毫秒的时间点

(3)int compareTo(Date anotherDate):比较两个日期的顺序,返回值只有 -1、0、1

注:日期排序时用compareTo()方法

(4)boolean before(Date when):测试此日期是否在指定日期之前

(5)boolean after(Date when):测试此日期是否在指定日期之后

(6)boolean equals(Object obj):比较两个日期的相等性

注:compareTo()、before()、after()、equals() 比较的都是getTime()返回的long值

(7)int hashCode():哈希码是getTime()返回long值的两部分的异或,即:(int) (this.getTime()^(this.getTime() >>> 32))

(8)String toString():默认调用,把此Date对象转换成以下形式的String:dow mon dd hh:mm:ss zzz yyyy

注:dow mon dd hh:mm:ss zzz yyyy :周 月 日 时:分:秒 时区 年

System.out.println(new Date().toString()); //Sun May 27 13:52:28 CST 2018

(9)Object clone():返回此对象的副本

4、日期对象和毫秒值之间的转换

(1)毫秒值 --> 日期对象:

原因:通过调用Date对象的方法对该日期中的各个字段(年、月、日等)进行操作

a. 通过Date对象的构造方法:new Date(System.currentTimeMillis());

b. 通过setTime()方法:Date date = new Date();    date.setTime(System.currentTimeMillis());

        //long time = System.currentTimeMillis();
        long time = 1527400740144L;
        System.out.println(time);
        Date date = new Date();
        date.setTime(time);
        System.out.println(date.toString());    //Sun May 27 13:59:00 CST 2018
        Date date2 = new Date(time);
        System.out.println(date2.toString());   //Sun May 27 13:59:00 CST 2018

(2)日期对象 --> 毫秒值:

原因:通过具体的数值进行运算

a. 通过getTime()方法:Date date = new Date();    long time = date.getTime();

        Date date = new Date();
        long time = date.getTime();
        System.out.println(time);   //1527402471677

注:获取毫秒值的另一个常用方法:System.currentTimeMillis();

5、Date中很多方法都已废弃,使用DateFormat和Calendar替代。DateFormat类格式化和解析日期字符串Calendar类实现日期时间字段之间的转换(把日期解释为年、月、日、时、分、秒)

二、java.text.Format

1、public abstract class Format:日期/时间 格式化抽象类

2、已知子类:DateFormat、MessageFormat、NumberFormat

注:Format中的子类都是不同步的,需要注意线程安全问题

3、Format定义了编程接口,将对象格式化为String(使用format()方法)和将String重新解析为对象(使用parseObject()方法)

4、构造方法

(1)protected Format():单独的构造方法,由子类的构造方法调用,通常是隐式的(Format类是抽象的,不能创建对象)

5、方法

Format是抽象类,其子类必须实现三个方法:format(Object obj, StringBuffer toAppendTo, FieldPosition pos)、formatToCharacterIterator(Object obj)、parseObject(String source, ParsePosition pos)

(1)String format(Object obj):格式化一个对象以生成一个字符串。等效于 format(obj, new StringBuffer(), new FieldPosition(0)).toString()

(2)abstract StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos):格式化一个对象,并将得到的文本添加到给定的字符缓冲区。如果pos参数标识了一个由format使用的字段,那么其索引就设置为第一次出现的此类字段的起始和结束索引

(3)AttributedCharacterIterator formatToCharacterIterator(Object obj):格式化字符串中所有属性的位置

(4)Object parseObject(String source) throws ParseException:从给定字符串的开始处解析文本以生成一个对象。此方法不可以使用给定字符串的全部文本

(5)abstract Object parseObject(String source, ParsePosition pos):解析字符串文本,生成一个对象。此方法试图解析从pos给定索引处开始的文本。如果解析成功,则将pos的索引更新到使用的最后一个字符之后的索引(不一定要解析直到字符串末尾的所有字符),并返回解析后的对象。更新的pos可以用来指示下一次调用此方法的起始点。如果发生错误,则不更改pos的索引,将pos的错误索引设置为错误发生处的字符的索引,并返回null

(6)Object clone():创建并返回此对象的一个副本

6、Format及其子类使用的简单类

(1)java.text.FieldPosition:Format及其子类用于在格式输出中标识字段的简单类。FieldPosition保持对格式输出中字段位置的两个索引进行跟踪:字段的第一个字符的索引和字段的最后一个字符的索引

(2)java.text.ParsePosition:Format及其子类所使用的简单类,用来在解析过程中跟踪当前位置(当前的解析位置、出错时的索引)

三、java.text.DateFormt

1、public abstract class DateFormat extends Format:日期/时间 格式化抽象类的子抽象类

2、已知子类:SimpleDateFormat

3、DateFormat 将 日期/时间 格式化,包括:日期-->文本、文本-->日期(日期为Date对象或者毫秒数)

4、DateFormat提供了很多类方法,以获得基于默认或给定语言环境和多种格式化风格的默认 日期/时间 Formatter(格式化风格包括:FULL、LONG、MEDIUM、SHORT)

5、构造方法

(1)protected DateFormat():创建一个新的DateFormat,子类初始化使用(DateFormat类是抽象的,不能创建对象)

6、工厂方法

DateFormat是抽象类,不能直接new对象,但可以通过静态工厂方法获取 日期/时间 对象,直接用 类名.工厂方法 即可(工厂是专门用于生产对象的地方,工厂方法都是静态的

作用:格式化不同语言环境、风格的日期。

(1)static final DateFormat getInstance():获取为日期和时间使用SHORT风格的默认日期/时间格式器

(2)static final DateFormat getDateInstance():获取日期格式器,该格式器具有默认语言环境的默认格式化风格

(3)static final DateFormat getDateInstance(int style):给定格式化风格

(4)static final DateFormat getDateInstance(int style, Locale aLocale):给定语言环境,给定格式化风格

(5)static final DateFormat getTimeInstance():获取时间格式器

(6)static final DateFormat getTimeInstance(int style)

(7)static final DateFormat getTimeInstance(int style, Locale aLocale)

(8)static final DateFormat getDateTimeInstance():获取日期/时间格式器

(9)static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle)

(10)static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)

7、其他方法

(1)final String format(Date date):将一个Date格式化为日期/时间字符串

(2)abstract StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)

(3)final StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition)

(4)Date parse(String source) throws ParseException:从给定字符串的开始解析文本,以生成一个日期。该方法不使用给定字符串的整个文本

(5)abstract Date parse(String source, ParsePosition pos):根据给定的解析位置开始解析日期/时间字符串

(6)Object parseObject(String source, ParsePosition pos):解析字符串中的文本,以生成一个Date

(7)Calendar getCalendar():获取与此日期/时间格式器关联的日历

(8)void setCalendar(Calendar newCalendar):设置此日期格式所使用的日历。最初为指定或默认的语言环境使用默认的日历

(9)NumberFormat getNumberFormat()获取此日期/时间格式器用于格式化和解析时间的数字格式器

(10)void setNumberFormat(NumberFormat newNumberFormat):允许用户设置数字格式器

(11)TimeZone getTimeZone():获取时区。返回与此DateFormat的日历相关联的时区

(12)void setTimeZone(TimeZone zone):为此DateFormat对象的日历设置时区

(13)boolean isLenient():判断日期/时间解析是否为不严格

(14)void setLenient(boolean lenient):指定日期/时间解析是否不严格。进行不严格解析时,解析程序可以使用启发式的方法来解释与此对象的格式不精确匹配的输入。进行严格解析时,输入必须匹配此对象的格式

(15)static Locale[] getAvailableLocales():返回所有语言环境的数组

8、DateFormat的clone()方法,里面调用除了自身之外的两个类的clone()方法

(1)Calendar --> TimeZone

(2)NumberFormat

9、注意:日期格式不是同步的。建议为每个线程创建独立的格式实例。如果多个线程同时访问一个格式,则它必须保持外部同步

        /**
         * 日期对象 --> 日期格式的字符串
         * DateFormat本身不能创建实例,直接获取实例,风格是固定的
         * 自定义的日期格式用SimpleDateFormat
         */

        //日期对象
        Date date = new Date();

        DateFormat format = DateFormat.getDateInstance();
        String str = format.format(date);
        System.out.println(str);    //2018-6-4

        //日期格式器,该格式器具有默认的风格
        format = DateFormat.getDateTimeInstance();
        //怎么格式化,日期格式器最清楚
        str = format.format(date);
        System.out.println(str);    //2018-6-4 10:57:06

        //指定风格:FULL
        format = DateFormat.getDateInstance(DateFormat.FULL);
        str = format.format(date);
        System.out.println(str);   //2018年6月4日 星期一

        //指定风格:LONG
        format = DateFormat.getDateInstance(DateFormat.LONG);
        str = format.format(date);
        System.out.println(str);   //2018年6月4日

        //指定风格:MEDIUM(和DateFormat.getDateInstance()相同)
        format = DateFormat.getDateInstance(DateFormat.MEDIUM);
        str = format.format(date);
        System.out.println(str);   //2018-6-4

        //指定风格:SHORT
        format = DateFormat.getDateInstance(DateFormat.SHORT);
        str = format.format(date);
        System.out.println(str);   //18-6-4
        /**
         * 日期格式的字符串 --> 日期对象
         * 使用DateFormat类中的parse()方法
         */

        String str = "2018-06-05";
        //String str = "2018年6月5日"; //抛异常ParseException
        //默认风格的对象,只支持对应格式的转换。如果 str="2018年6月5日",会抛出ParseException。或使用DateFormat.getDateInstance(DateFormat.LONG)
        DateFormat dateFormat = DateFormat.getDateInstance();
        //抛出异常,必须是日期格式的字符串才可以转换
        Date date = dateFormat.parse(str);
        System.out.println(date);   //Tue Jun 05 00:00:00 CST 2018

注:使用指定风格FULL、LONG、MEDIUM、SHORT,可以针对date(日期)、time(时间),也可以针对dateTime(日期, 时间)

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        String str = dateFormat.format(date);
        System.out.println(str);    //2018年6月4日 CST 下午11:36:04

四、java.text.SimpleDateFormat

1、SimpleDateFormat:格式化(日期-->文本)和解析(文本-->日期)日期的具体类。可以选择任何用户定义的日期-时间格式的模式。

2、构造方法

(1)SimpleDateFormat()

(2)SimpleDateFormat(String pattern):pattern是描述日期和时间格式的模式,即自定义的模式

(3)SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols):用给定的模式和日期符号构造SimpleDateFormat。formatSymbols是要用来格式化的日期格式符号

注:DateFormatSymbols类是一个公共类,用于封装可本地化的日期-时间格式化数据。DateFormat和SimpleDateFormat都使用DateFormatSymbols封装此信息。通常不应直接使用DateFormatSymbols,建议最好使用DateFormat类的工厂方法创建日期-时间格式器(formatter):getXxxInstance()。这些方法自动为格式器创建一个DateFormatSymbols

(4)SimpleDateFormat(String pattern, Locale locale)locale是要被使用的语言环境

3、方法

(1)StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos):将给定的Date格式化为日期/时间字符串,并将结果添加到给定的StringBuffer

(2)Date parse(String text, ParsePosition pos):解析字符串的文本,生成Date

(3)AttributedCharacterIterator formatToCharacterIterator(Object obj)

(4)void setDateFormatSymbols(DateFormatSymbols newFormatSymbols):设置此日期格式的日期和时间格式符号

(5)void applyPattern(String pattern):将给定模式字符串应用于此日期格式

(6)void applyLocalizedPattern(String pattern):将给定的本地化模式字符串应用于此日期格式

(7)String toPattern():返回描述此日期格式的模式字符串

(8)String toLocalizedPattern():返回描述此日期格式的本地化模式字符串

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        String str = simpleDateFormat.format(date);
        System.out.println(str);    //2018/6/4 下午10:42

        simpleDateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
        str = simpleDateFormat.format(date);
        System.out.println(str);    //2018-06-04 22:42:58

        System.out.println(new SimpleDateFormat().toPattern());     //y/M/d ah:mm
        System.out.println(simpleDateFormat.toPattern());           //yyyy-MM-dd HH:mm:ss

4、DateFormat是抽象类,不能创建对象,用getXxxInstance()方法直接获取对象,其格式器风格已经被固化在对象中(调用getXxxInstance()方法时已经new好对象了)。想要自定义风格的格式器,自己创建对象,用SimpleDateFormat

        /**
         * 日期对象 --> 日期格式的字符串
         * 使用可以自定义的日期格式器SimpleDateFormat
         */

        Date date = new Date();
        //自定义风格
        DateFormat format = new SimpleDateFormat("yyyy--MM--dd");
        String str = format.format(date);
        System.out.println(str);    //2018--06--05

        //DateFormat使用的也是SimpleDateFormat子类
        DateFormat dateFormat = DateFormat.getDateInstance();
        System.out.println(dateFormat); //java.text.SimpleDateFormat@ef7951d7
        /**
         * 日期格式的字符串 --> 日期对象
         * 使用SimpleDateFormat对象自定义格式,再用parse()方法进行转换
         */

        String str = "2018--06--05";
        //默认没有的风格 -- 自定义
        DateFormat dateFormat = new SimpleDateFormat("yyyy--MM--dd");
        //抛出异常,必须是日期格式的字符串才可以转换
        Date date = dateFormat.parse(str);
        System.out.println(date);   //Tue Jun 05 00:00:00 CST 2018

5、练习

    /**
     * 练习:“2012-3-17”到“2012-4-6”中间有多少天
     * 思路:两个日期相减,能减的可以是毫秒值
     * 步骤:
     * (1)将日期格式的字符串转成Date对象
     * (2)将Date对象转成毫秒值
     * (3)相减,再变成天数
     */
    public static int getDays(String str1, String str2) throws ParseException {

        //将日期字符串转成日期对象(二选一,根据情况看使用哪个)
        DateFormat dateFormat = DateFormat.getDateInstance();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date1 = dateFormat.parse(str1);
        Date date2 = dateFormat.parse(str2);

        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long time = Math.abs(time1 - time2);

        int days = getDays(time);
        return days;
    }

    private static int getDays(long time) {
        int days = (int) (time/1000/60/60/24);
        return days;
    }

    public static void main(String[] args) throws ParseException {
        int days = getDays("2012-3-17", "2012-3-18");
        System.out.println(days);
    }

五、java.util.Calendar

1、public abstract class Calendar

2、Calendar为操作日历字段YEAR、MONTH、DAY_OF_MONTH、HOUR等提供了一些方法

3、抽象类不能创建对象,要通过工厂获取对象。根据对象的输出结果(键值对),想要获取值,需要通过键拿值

        Calendar c= Calendar.getInstance();
        System.out.println(c);

        /** 输出结果:
         *  time=1528268859185,
         *  areFieldsSet=true,
         *  areAllFieldsSet=true,
         *  lenient=true,
         *  zone=sun.util.calendar.ZoneInfo[
         *      id="Asia/Shanghai",
         *      offset=28800000,
         *      dstSavings=0,
         *      useDaylight=false,
         *      transitions=19,
         *      astRule=null
         *  ],
         *  firstDayOfWeek=1,
         *  minimalDaysInFirstWeek=1,
         *  ERA=1,
         *  YEAR=2018,
         *  MONTH=5,
         *  WEEK_OF_YEAR=23,
         *  WEEK_OF_MONTH=2,
         *  DAY_OF_MONTH=6,
         *  DAY_OF_YEAR=157,
         *  DAY_OF_WEEK=4,
         *  DAY_OF_WEEK_IN_MONTH=1,
         *  AM_PM=1,
         *  HOUR=3,
         *  HOUR_OF_DAY=15,
         *  MINUTE=7,
         *  SECOND=39,
         *  MILLISECOND=185,
         *  ZONE_OFFSET=28800000,
         *  DST_OFFSET=0
         */
        //根据对象返回的结果(是一堆键值对),通过键拿值
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;  //月份从0开始
        int day = c.get(Calendar.DAY_OF_MONTH);
        int week = c.get(Calendar.DAY_OF_WEEK);
        System.out.println(year + "-" + month + "-" + day + " " + getWeek(week)); //2018-6-6 星期三


    private static String getWeek(int i){
        String[] weeks = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        return weeks[i];
    }

4、字段:可以通过 类名.字段名 获取相应的值

eg:

(1)Calendar.JANUARY  一月(值为0), Calendar.SUNDAY 星期日(值为1), Calendar.MONDAY 星期一(值为2)

         Calendar.AM 上午(值为0), Calendar.PM 下午(值为1)

         Calendar.DATE = Calendar.DAY_OF_MONTH 值为当前日

(2)Calendar.getInstance().get(Calendar.HOUR_OF_DAY值为当前小时(24小时制)

         Calendar.getInstance().get(Calendar.HOUR) 值为当前小时(十二小时制)

         Calendar.getInstance().get(Calendar.MINUTE) 值为当前分钟

         Calendar.getInstance().get(Calendar.SECOND) 值为当前秒

         Calendar.getInstance().get(Calendar.MILLISECOND) 值为当前毫秒

         Calendar.getInstance().get(Calendar.YEAR 值为当前年

         Calendar.getInstance().get(Calendar.MONTH 值为当前月,1月值为0,2月值为1...

         Calendar.getInstance().get(Calendar.DATE )  = Calendar.getInstance().get(Calendar.DAY_OF_MONTH) 值为当前日

         Calendar.getInstance().get(Calendar.DAY_OF_WEEK) 值为当前星期数,周日值为1,周一值为2...

         Calendar.getInstance().get(Calendar.WEEK_OF_MONTH) 值为当前月中的星期数

         Calendar.getInstance().get(Calendar.WEEK_OF_YEAR) 值为当前年中的星期数

注:值一般都是从1开始的,只有月份是从0开始的

5、构造方法

Calendar是抽象类,不能创建对象。其构造方法是给子类初始化用的

(1)protected Calendar():构造一个带有默认时区和语言环境的Calendar

(2)protected Calendar(TimeZone zone, Locale aLocale):构造一个带有指定时区和语言环境的Calendar

6、工厂方法

(1)static Calendar getInstance()

(2)static Calendar getInstance(Locale aLocale)

(3)static Calendar getInstance(TimeZone zone)

(4)static Calendar getInstance(TimeZone zone, Locale aLocale)

7、方法

(1)int get(int field):返回给定日历字段的值,即获取当前xxx时间

(2)void set(int field, int value):设置指定时间

(3)final void set(int year, int month, int date):设置日历字段YEAR、MONTH、DAY_OF_MONTH的值

(4)final void set(int year, int month, int date, int hourOfDay, int minute)

(5)final void set(int year, int month, int date, int hourOfDay, int minute, int second)

(6)abstract void add(int field, int amount):为给定的日历字段添加或减去指定的时间量,即可以引起日期/时间的偏移

eg:从当前日历时间减去5天:add(Calendar.DAY_OF_MONTH, -5)

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2018, 11, 20); //2018年12月20日星期五
        //calendar.add(Calendar.MONTH, 2);    //2019年2月20日星期四
        calendar.add(Calendar.DAY_OF_MONTH, 12);    //2019年1月1日星期三
        showDate(calendar);
    }

    private static void showDate(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        System.out.println(year + "年" + month + "月" + day + "日" + getWeek(week));
    }

    private static String getWeek(int week) {
        String[] weeks = {"", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
        return weeks[week];
    }

(7)boolean before(Object when)判断此Calendar表示的时间是否在指定Object表示的时间之前。等效于compareTo(when)<0

(8)boolean after(Object when):判断此Calendar表示的时间是否在指定Object表示的时间之后。等效于compareTo(when)>0

(9)int compareTo(Calendar anotherCalendar):比较两个Calendar对象表示的时间值(从历元至现在的毫秒偏移量)

(10)final void clear():将此Calendar的所有日历字段值和时间值(从历元至现在的毫秒偏移量)设置成未定义

(11)final void clear(int field)

        /**
         * clear():将日期的年月日时分秒都恢复到格林尼治时间
         * clear(field):将field对应的日期/时间恢复到格林尼治时间,但日和小时(HOUR_OF_DAY、HOUR、AM_PM)除外
         */
        Calendar calendar = Calendar.getInstance(); //2018年12月20日星期五 23时34分1秒
        //calendar.clear(Calendar.YEAR);  //1970年12月20日星期一 23时34分1秒
        //calendar.clear(Calendar.DAY_OF_MONTH);  //2018年12月20日星期五 23时34分1秒
        //calendar.clear(Calendar.HOUR_OF_DAY);   //2018年12月20日星期五 23时34分1秒
        //calendar.clear(Calendar.SECOND);    //2018年12月20日星期五 23时34分0秒
        calendar.clear();   //1970年1月1日星期五 0时0分0秒

(12)final Date getTime():返回一个表示此Calendar时间值(从历元至现在的毫秒偏移量)的Date对象

(13)long getTimeInMillis():返回此Calendar的时间值(从历元至现在),以毫秒为单位 

(14)final void setTime(Date date):使用给定的Date设置此Calendar的时间

(15)void setTimeInMillis(long millis):用给定的long值设置此Calendar的当前时间值。millis是以从历元至现在所经过的毫秒数

(16)void complete():填充日历字段中所有未设置的字段

8、Calendar类中需要掌握的常见方法:get、set、add

9、练习

https://pan.baidu.com/s/1yJfJomQX6pCtCQU4sG0qdQ    密码:fdte


猜你喜欢

转载自blog.csdn.net/ruyu00/article/details/80462658