常用API

Date

SimpleDateFormat

Calendar

calendar是抽象类不能直接创建对象,可以通过静态方法调用

JDK8时间

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Set;

public class test8 {
    public static void main(String[] args) {
        //ZoneId
        //获取所有时区,共600
        Set<String> zoneIds = ZoneId.getAvailableZoneIds();
        //获取系统默认时区
        ZoneId zoneId = ZoneId.systemDefault();
       //获取指定时区
        ZoneId zoneId1 = ZoneId.of("Asia/Shanghai");//手动添加

        //获取当前标准时间(我国的需要加八个小时)
        Instant now = Instant.now();
       //根据秒/毫秒/纳秒获取Instant对象
        //从时间原点开始
        Instant instant = Instant.ofEpochSecond(10);//秒
        Instant.ofEpochMilli(1000);//毫秒
        Instant.ofEpochSecond(1,1000000000);//一秒加上1000000000纳秒
        //指定时区atZone
        ZonedDateTime zonedDateTime = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
        //判断时间前后,返回值是boolean
        Instant instant1 = Instant.ofEpochSecond(1);
        Instant instant2 = Instant.ofEpochSecond(2);
        instant1.isBefore(instant2);//true
        instant1.isAfter(instant2);//false
        //增加时间和减少时间
        instant1.minusSeconds(1);//减一秒
        instant2.plusSeconds(1);//增加一秒


        //带时区的时间
        ZonedDateTime now1 = ZonedDateTime.now();
        //指定年月日等
        ZonedDateTime zonedDateTime1 = ZonedDateTime.of(2023, 10, 1, 10,
                10, 10, 0, ZoneId.of("Asia/Shanghai"));
        //修改时间,增加时间,减少时间
        zonedDateTime1.withYear(2024);//修改年份
        zonedDateTime1.minusSeconds(1);//减少一秒
        zonedDateTime1.plusSeconds(2);//增加两秒
        /*
         JDK8后时间对象是不可变的
         不管是修改,增加,减少,都会产生新的时间
         */

        //日期格式化类
        //获取对象
        ZonedDateTime t=Instant.now().atZone(ZoneId.of("Asia/Shanghai"));
        //解析格式化
        DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //按照指定格式化
        System.out.println(dateTimeFormatter.format(t));


        //日历类
        /*LocalDate, LocalTime,LocalDateTime
        now:获取当前时间对象
        of()获取指定时间
        getXXX获取日历中年,月,日等
        isBefore,isAfter
        with修改
        minus减少
        plus增加
         */
        

     /*工具类
      Duration(秒,纳秒),Period(年,月,日),ChronoUnit(所有单位)
      */
    }
}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值