zoukankan      html  css  js  c++  java
  • review13

    Date与Calendar类

    Date类和Calendar类属于java.util包。

    Date类

    1.使用无参数构造方法

    使用Date类的无参构造方法创建的对象可以获取本机的当前日期和时间,例如:

    Date nowTime = new Date();

    2.使用带参数的构造方法

    计算机系统将其自身的时间的“公元”设置在1970年1月1日0时(格林威治时间),方法使用情况如下所示:

    Date date = new Date(1000);

    本地时区是北京时区,“公元”时间是,1970年01月01日08时00分00秒,而上述的date就是1970年01月01日08时00分01秒。

    使用System类的静态方法public long currentTimeMillis()获取系统当前时间距离“公元”时间过去的毫秒数。

    Calendar类

    使用Calendar类的static方法getInstance()可以初始化一个日历对象,如:

    Calendar calendar = Calendar.getInstance();

    Calendar对象可以调用方法:

    public final void set(int year, int month, int date);

    public final void set(int year, int month, int date, int hour, int minute);

    public final void set(int year, int month, int date, int hour, int minute, int second);

    将日历设置在任何一个时间,如:
    calendar.set(2014, 5, 25);

    就是将日历时间设置在2014年6月25日。

    Calendar对象调用方法public int get(int field)可以获取有关年份、月份、小时、星期等信息,参数field的有效值由Calendar的静态常量指定,例如:

    calendar.get(Calendar.MONTH);

    返回一个整数,如果该整数是0表示当前日历是在1月。

    calendar.get(Calendar.DAY_OF_WEEK);

    返回一个整数,如果该整数是1表示星期日,7表示星期六。

    public long getTimeInMillis()方法获取距离设置的时间的毫秒数。

    代码展示如下所示:

    public class Test10 {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Date nowTime = new Date();
            System.out.println(nowTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            System.out.print("现在的时间是: ");
            System.out.print(year + "年" + month + "月" + day + "日");
            System.out.println(hour + "时" + minute + "分" + second + "秒");
            calendar.set(2014, 5, 25);
            long time1 = calendar.getTimeInMillis();
            calendar.set(2018, 6, 6);
            long time2 = calendar.getTimeInMillis();
            long subDay = (time2 - time1 ) / (24 * 60 * 60 * 1000);
            System.out.println("到现在为止已经经过了" + subDay + "天");
            
        }
    
    }

    运行结果如下所示:

  • 相关阅读:
    【论文阅读】A practical algorithm for distributed clustering and outlier detection
    第11组 团队Git现场编程实战
    第11组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    第11组 团队展示
    第一次结对编程作业
    第一次个人编程作业
    第一次博客作业
    (转)script标签到底该放在哪里
  • 原文地址:https://www.cnblogs.com/liaoxiaolao/p/9275723.html
Copyright © 2011-2022 走看看