zoukankan      html  css  js  c++  java
  • Java常用API——时间类

    前言:Java.util.*工具包中,包含了集合框架,旧集合类,事件模型,日期和时间设施,国际化和其他使用程序类

    (字符串、随机数生成器和位数组)

    一、日期类Date

     1.概述

      Date是一个薄包装类,没有定义很多方法,而且很多方法已经被弃用,但是它仍是常被使用的类。

      Date它允许将日期解释为年,月,日,小时,分钟和第二个值,

      而且DateFormat类应用于格式化和解析日期字符串,允许JDCBC将其标识为SQLDate值。

      public class Date extends Object
       implements Serializable, Cloneable, Comparable<Date>

     2.构造方法

      目前在使用的构造方法只有:Date();

      Date date = new Date();

      Date date = new Date(long);

      分配一个Date对象,并初始化它,以便它代表它被分配的时间,测量到最近的毫秒。

     3.常用方法

      boolean after(Date when) => 测试此日期是否在指定日期之后。

      boolean before(Date when) => 测试此日期是否在指定日期之前。

      Object clone() => 返回此对象的副本

      int compareTo(Date anotherDate) => 比较两个日期进行比较(-1、0、1)

      boolean equals(Object obj) => 比较连个日期是否平等

      static Date from(Instant instant) => 从Instant对象获取一个Date实例

      long getTime()  =>返回自1970年1月1日以来,由此 Date对象表示的00:00:00 GMT的毫秒 数 。

     4.应用案例 

    public class DateTest {
        public static void main(String[] args) {
            //day03.DateFormat.Date(n)表示距离1970年1月1日0点0分0秒的时间(以毫秒为单位计算)
            Date date = new Date(0);
            System.out.println(date);
    
            Date now = new Date();
            System.out.println(now.after(date));  
            System.out.println(now.before(date));  
            //getTime()方法表示该Date对象距离1970年1月1日0点0分0秒以毫秒计算的时间
            System.out.println(now.getTime());
        }
    }
    

      

    二、Calendar日历类

     1.概述

      Calendar类时相对比较新的日期类,它是一个抽象类,

      Calendar类可以为在某一特定时刻和一组之间的转换的方法calendar fields如YEAR , MONTH , DAY_OF_MONTH , HOUR等,以及用于操纵该日历字段。

      public abstract class Calendar extends Object
        implements Serializable,  Cloneable, Comparable<Calendar>

     2.初始化

      Calendar日共了一种类方法getInstance(),用于获取此类的一般有用的对象。

      Calendar的getInstance方法返回一个Calendar对象,其 日历字段已使用当前日期和时间进行初始化。

      eg.  Calendar calendar = Calendar.getInstance();

     3.常用的方法

      boolean after(Object when) => 返回 Calendar是否 Calendar指定时间之后的时间 Object 。 
        boolean before(Object when) => 返回此 Calendar是否 Calendar指定的时间之前指定的时间 Object 。

      void set(int year, int month, int date) => 设置日历字段中的值 YEAR , MONTH和 DAY_OF_MONTH 。

      add(int field, int amount) =>  根据日历的规则,将指定的时间量添加或减去给定的日历字段。
         roll(int field, int amount)  =>  将指定(签名)金额添加到指定的日历字段,而不更改较大的字段。

     4.常用的类变量

      public static final int YEAR => get字段号和set表示年份

      public static final int MONTH => get和set字段编号表示月份。
         (注意genInstance获得的月份为0~11,代表1到12月)
         public static final int DATE => get字段编号和set本月的日期。
         public static final int WEEK_OF_YEAR =>
         public static final int WEEK_OF_MONTH =>
         public static final int DAY_OF_YEAR =>

     5.应用案例

    public class CalendarDemo {
        public static void main(String[] args) {
            //初始化日期类Calendar
            Calendar rightNow = Calendar.getInstance();
            System.out.println(rightNow.toInstant());
            System.out.println("目前时间为:" +
                    rightNow.get(Calendar.YEAR) + "年" +
                    //注意getInstance获得的月份范围为0~11,需要+1才为正确月份
                    (rightNow.get(Calendar.MONTH)+1) + "月" +
                    rightNow.get(Calendar.DATE) + "日"
            );
    
            Calendar calendar = Calendar.getInstance();
            calendar.set(2008,11,2,14,30);
            System.out.println(calendar.get(Calendar.YEAR) + " " + 
                    calendar.get(Calendar.MONTH) + " " +
                    calendar.get(Calendar.DATE)); System.out.println("=============================="); calendar.add(Calendar.YEAR,-10); System.out.println(calendar.get(Calendar.YEAR) + " " +
                    calendar.get(Calendar.MONTH) + " " +
                    calendar.get(Calendar.DATE)); System.out.println("=============================="); calendar.roll(Calendar.MONTH,+3); System.out.println(calendar.get(Calendar.YEAR) + " " +
                    calendar.get(Calendar.MONTH) + " " +
                    calendar.get(Calendar.DATE)); System.out.println("=============================="); } } 

    三、DateFormat => 输出的是xxxx年xx月xx日

     1.概述

      DateFormat是格式化日期,它可以格式化和解析任何区域设置的日期。

      DateFormat是一个抽象类,不能直接实例化,可以通过getDateFormatInstance类方法定义。

      public abstract class DateFormat extends Format

     2.构造方法

      public static final DateFormat getDateInstance()
         eg.  DateFormat df = DateFormat.getDateInstance();

     3.主要方法

      String format(Date date) => 将日期格式化成日期/时间的字符串。

      Date parse(String source) => 从给定字符串的开始解析文本以生成日期。

     4.应用案例

    public class DateFormatDemo {
        public static void main(String[] args) {
            DateFormat df = DateFormat.getDateInstance();
            System.out.println(df);
            String t1 = df.format(new Date());
            System.out.println(t1);
            Date date = null;
            try {
                date = df.parse(t1);
                System.out.println(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }
    

      

    四、SimpleDateFormat

     1.概述

      SimpleDateFormat实现了DateFormat抽象类,它是实现类。

      SimpleDateFormat允许从选择日期时间格式化的任何用户定义的模式开始。

      public class SimpleDateFormat extends DateFormat

     2.构造方法

      SimpleDateFormat sdf = new SimpleDateFormat();

      SimpleDateFormat sdf = new SimpleDateFormat(String pattern);

     3.常用方法

      void applyPattern(String pattern) => 将给定的模式字符串应用于此日期格式。

      String format(Date date) => 将日期格式化成日期/时间字符串。

      Date parse(String source) => 从给定字符串的开始解析文本以生成日期。

     4.应用案例

    public class SimpleDateFormatDemo {
        public static void main(String[] args) {
            SimpleDateFormat smf = new SimpleDateFormat();
            Calendar calendar = Calendar.getInstance();
            String s = "2019年2月2日 星期六 19时10分55秒";
            String pattern = "yyyy年MM月dd日 E HH时mm分ss秒";
            smf.applyPattern(pattern);
            try {
                Date date = smf.parse(s);
                System.out.println(date.getTime());
                calendar.setTime(date);
                System.out.println(calendar.getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }
    

      

    实战小案例

      需求:计算自己活了多少天!

    public class LivingDay {
        public static void main(String[] args) {
            //获取用户生日和当前时间
            long livingdays = 0;
            while (true) {
                System.out.println("请输入您的生日!格式样例:1998-02-09");
                Scanner in = new Scanner(System.in);
                String birthday = in.nextLine();
                SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date bornDate = smf.parse(birthday);
                    Date nowDate = new Date();
                    //调用clacDays方法计算时间
                    livingdays = calcDays(nowDate, bornDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //输出结果时间
                System.out.println("您已经度过了" + livingdays + "天的美好时光!");
            }
        }
    
        /**
         * 计算两个时期之间的天数
         * @param nowDate
         * @param bornDate
         * @return
         */
        private static Long calcDays(Date nowDate, Date bornDate) {
            long days = 0;
            long daysTS = nowDate.getTime() - bornDate.getTime();
            days = daysTS/1000/60/60/24;
            return days;
        }
    }

       总结几个重要的方法!!

      1.SimpleDateFormat的parse()  =>将字符串转化为Date类型的日期

      2.Date的getTime()       =>将Date类型的日期转化为long类型的时间戳

      3.Date(long)的构造方法      =>将long类型时间戳转化为Date类型时间

      4.SimpleDateFormat的format()     =>将Date类型日期转化为StringBuffer类型的字符串时间

  • 相关阅读:
    JS中解析JSON。
    对不同浏览器实现图片旋转。
    FF和IE内容不透明,字体透明。
    C# 通过身份证查询出生日期
    C# v3微信 access token 过期处理的问题
    C# 微信v3退款
    codesmith生成java类
    IOS调用WCF服务,WCF服务器进行上传图片
    安装VS 2013遇到的问题,及解决方案
    接口,个人理解
  • 原文地址:https://www.cnblogs.com/HelloBigTable/p/10351041.html
Copyright © 2011-2022 走看看