一、Date类

  在JDK1.0中,Date类是唯一的一个代表时间的类,但是由于Date类不便于实现国际化,所以从JDK1.1版本开始,推荐使用Calendar类进行时间和日期处理。这里简单介绍一下Date类的使用。

  1、使用Date类代表当前系统时间

Date date = new Date();

  使用Date类的默认构造方法创建出来的对象就代表当前的时间,由于Date类覆盖了toString()方法。所以可以直接输出Date类型的对象,显示的结果如下:

Thu Jan 11 18:32:40 CST 2018

  在该格式中,Thu代表Thursday(周四),Jan代表Janauary(一月),11代表11号,CTS代表China Standard Time(中国标准时间,也就是北京时间(东八区))。

  2、使用Date类代表指定时间

  Date date=new Date(2017-1900,1-1,11);
  System.out.println(date);

  使用带参的构造方法,可以构造指定日期的Date对象,Date类中年份的参数应该是实际需要代表的年份减去1990,实际需要代表的月份减去1以后的值。显示结果如下:

Wed Jan 11 00:00:00 CST 2017

  实际代表的年月日时分秒的日期对象和这个类似

  3、获取Date对象中的信息

Java的Date类与Calendar

package com.sc.util;

import java.util.Date;

public class DateTest {
    
    public static void main(String[] args) {
        Date d=new Date();
        int year = d.getYear()+1990;
        int month=d.getMonth()+1;
        int date=d.getDate();
        int hour=d.getHours();
        int minute=d.getMinutes();
        int second=d.getSeconds();
        int day=d.getDay();
        System.out.println("年份:"+year);
        System.out.println("月份:"+month);
        System.out.println("日期:"+date);
        System.out.println("小时:"+hour);
        System.out.println("分钟:"+minute);
        System.out.println("秒:"+second);
        System.out.println("星期:"+day);
    }

}
View Code

相关文章: