java经常使用类库--日期类总结

java经常使用类库--日期类总结

一、Date类经常使用的东西

/**
* 方法1:使用Date中的getTime()方法,能够获取到从1970年1月1日00:00:00 GMT以来的毫秒值
*/
public class Demo04 {
    public static void main(String[] args) throws ParseException {
        Date date = new Date();
        System.out.println(date.getTime());
    }
}

二、DateFormat类经常使用的东西

public class Demo05 {
    public static void main(String[] args) throws ParseException {
        testSimpleDateFormat();
    }

    /**
     * 测试 DateFormat这个类的经常使用方法
     * DateFormat是一个抽象类,因此不能实例化,咱们要使用它的实现类为SimpleDateFormat
     */
    public static void testSimpleDateFormat() throws ParseException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm ss");
        //把Date对象转换为时间字符串
        String date1 = simpleDateFormat.format(date);
        //把字符串转换为Date对象
        Date date2 = simpleDateFormat.parse(date1);
        System.out.println(date1);
        System.out.println(date2);
    }
}
一、SimpleDateFormat的构造方法
二、SimpleDateFormat把Date对象转化为时间字符串
三、SimpleDateFormat把时间字符串转化为Date对象

三、Calendar类

一、Calendar获取对象的方式

Calendar calendar = Calendar.getInstance();
注意事项:
	一、Calendar是一个抽象类不能直接实例化建立对象
	二、Calendar是静态修饰的代码,能够直接Calendar.XXX方法的方式调用方法
	三、建立Calendar类的方式为:Calendar.getInstance()

那么新实例化的类究竟是个啥?咱们来看源码java

if (aLocale.hasExtensions()) {
            String caltype = aLocale.getUnicodeLocaleType("ca");
            if (caltype != null) {
                switch (caltype) {
                case "buddhist":
                cal = new BuddhistCalendar(zone, aLocale);
                    break;
                case "japanese":
                    cal = new JapaneseImperialCalendar(zone, aLocale);
                    break;
                case "gregory":
                    cal = new GregorianCalendar(zone, aLocale);
                    break;
                }
            }
        }
/**
* 这个代码中咱们能够看到3个类:
* BuddhistCalendar
* JapaneseImperialCalendar
* GregorianCalendar
* 表示这Calendar这个类根据你不一样的地区而建立它不一样的实例化类。
*/

二、取出日历里面的年月日

首先,咱们能够点开Calendar的源码查看,能够看到一个数组数组

/**
* Calendar中的年月日都存储在这样一个数组中
*/
protected int  fields[];

//因此当咱们去获取它的年月日的时候,实际上传递的是一个数组的下标
//例如:
Calendar cl = Calendar.getInstance();
int year = cl.get(Calendar.Year);
//此时这个get中传递的参数其实是一个下标值

三、Calendar经常使用方法

一、获取年月日  ---->  get
二、设置年月日  ---->  set
三、添加年月日  ---->  add
四、获取Date对象  ---->  getTime
五、获取年月日的最大值  ---->  getActualMaxmum
相关文章
相关标签/搜索