JDK -- 日期时间类

目录

Date

SimpleDateFormat

Calendar

LocalDate -- JDK8 后提供日期类(年月日)

LocalTime --  JDK8 后提供时间类(时分秒)

LocalDateTime -- JDK8 后提供日期时间类(年月日时分秒)

Instant -- JDK8 后提供时间戳类

DateTimeFormatter -- JDK8 后提供格式化日期类

Period -- JDK8 后提供日期间隔类

Duration-- JDK8 后提供时间间隔类

ChronoUnit -- JDK8 提供日期时间间隔工具类(推荐)


Date

 // 1、创建一个Date类的对象:代表系统此刻日期时间对象
        Date d = new Date();
        // 2、获取时间毫秒值
        long time = d.getTime();

        // 1、得到当前时间
        Date d1 = new Date();
        System.out.println(d1);

        // 2、当前时间往后走 1小时  121s
        long time2 = System.currentTimeMillis();
        time2 += (60 * 60 + 121) * 1000;

        // 3、把时间毫秒值转换成对应的日期对象。
        Date d2 = new Date(time2);

        Date d3 = new Date();
        d3.setTime(time2);

SimpleDateFormat

        // 1、日期对象
        Date d = new Date();
        // 2、格式化这个日期对象 (指定最终格式化的形式)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
        // 3、开始格式化日期对象成为喜欢的字符串形式
        String rs = sdf.format(d);
        // 4、格式化时间毫秒值
        // 需求:请问121秒后的时间是多少
        long time1 = System.currentTimeMillis() + 121 * 1000;
        String rs2 = sdf.format(time1);

        String dateStr = "2021年08月06日 11:11:11";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date d2 = sdf.parse(dateStr);
        //往后走2天 14小时 49分 06秒
        long time = d2.getTime() + (2L*24*60*60 + 14*60*60 + 49*60 + 6) * 1000;
        //格式化这个时间毫秒值就是结果
        System.out.println(sdf.format(time));

Calendar

        // 1、拿到系统此刻日历对象
        Calendar cal = Calendar.getInstance();
        System.out.println(cal); //可以看到所有Calendar的field
        // 2、获取日历的信息:public int get(int field):取日期中的某个字段信息。
        int year = cal.get(Calendar.YEAR);
        int mm = cal.get(Calendar.MONTH) + 1;
        int days = cal.get(Calendar.DAY_OF_YEAR) ;
        // 3、public void set(int field,int value):修改日历的某个字段信息。
        cal.set(Calendar.HOUR , 12);
        // 4.public void add(int field,int amount):为某个字段增加/减少指定的值
        // 请问64天后是什么时间
        cal.add(Calendar.DAY_OF_YEAR , 64);
        cal.add(Calendar.MINUTE , 59);
        //  5.public final Date getTime(): 拿到此刻日期对象。
        Date d = cal.getTime();
        //  6.public long getTimeInMillis(): 拿到此刻时间毫秒值
        long time = cal.getTimeInMillis();

LocalDate -- JDK8 后提供日期类(年月日)

        // 1、获取本地日期对象。
        LocalDate nowDate = LocalDate.now();
        System.out.println("今天的日期:" + nowDate);//今天的日期:
        int year = nowDate.getYear();
        System.out.println("year:" + year);
        int month = nowDate.getMonthValue();
        System.out.println("month:" + month);
        int day = nowDate.getDayOfMonth();
        System.out.println("day:" + day);

       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值