Java中新旧日期时间的使用

一、旧的日期时间API
1、Date 类提供的常用方法有:
getTime():(自1970年1月1日经历的毫秒数值)获取两个日期,然后比较。
before():若当调用此方法的Date对象在指定日期之前返回true,否则返回false。
after():若当调用此方法的Date对象在指定日期之后返回true,否则返回false。
equals():当调用此方法的Date对象和指定日期相等时候返回true,否则返回false。
compareTo():比较当调用此方法的Date对象和指定日期。两者相等时候返回0。调用对象在指定日期之前则返回负数。调用对象在指定日期之后则返回正数
    
2、Calendar类提供的常用方法有:
get():返回给定日历字段的值。
set():将给定的日历字段设置为给定值。
add():根据日历的规则,为给定的日历字段添加或减去指定的时间量。
getTime():返回一个表示此Calendar时间值(从历元到现在的毫秒偏移量)的Date对象。

二、Java 8日期时间API中主要涉及到以下类和接口:
1、java.time.LocalDate:表示一个ISO-8601格式的日期,不包含时间信息,LocalDate 类提供了很多方法来操作日期对象,以下是一些常用的方法:
getYear():获取当前日期的年份。
getMonth():获取当前日期的月份。
getDayOfMonth():获取当前日期的日子。
plusDays(long daysToAdd):增加指定天数后的日期对象。
minusDays(long daysToSubtract):减去指定天数后的日期对象。
isLeapYear():判断当前年份是否是闰年。

2、java.time.LocalTime:表示一个ISO-8601格式的时间,不包含日期信息,LocalTime 类提供了很多方法来操作时间对象,以下是一些常用的方法:
getHour():获取当前时间的小时数。
getMinute():获取当前时间的分钟数。
getSecond():获取当前时间的秒数。
plusHours(long hoursToAdd):增加指定小时数后的时间对象。
minusMinutes(long minutesToSubtract):减去指定分钟数后的时间对象。


3、java.time.LocalDateTime:表示一个ISO-8601格式的日期时间,LocalDateTime 类提供了很多方法来操作日期和时间对象,以下是一些常用的方法:
toLocalDate():将当前日期时间转换为日期对象。
toLocalTime():将当前日期时间转换为时间对象。
plusDays(long daysToAdd):增加指定天数后的日期时间对象。
minusMonths(long monthsToSubtract):减去指定月份数后的日期时间对象。


4、java.time.Instant:表示从‘1970-01-01T00:00:00Z’开始的秒数,Instant 类提供了很多方法来操作日期时间对象,以下是一些常用的方法:
getEpochSecond():获取当前 Instant 对象自 1970 年 1 月 1 日开始的秒数。
plusMillis(long millisToAdd):增加指定毫秒数后的 Instant 对象。
minusNanos(long nanosToSubtract):减去指定纳秒数后的 Instant 对象。


5、java.time.Duration:表示两个时刻之间的持续时间或时间段,Duration类提供了很多有用的方法,例如:
getSeconds():获取Duration实例中的总秒数
toDays():获取Duration实例中的总天数
plus(long amountToAdd, TemporalUnit unit):将指定的时间单元添加到该Duration实例
plusHours(long hoursToAdd):将指定的小时数添加到该Duration实例
plusMinutes(long minutesToAdd):将指定的分钟数添加到该Duration实例


6、java.time.Period:表示两个日期之间的天数、月数或年数,Period类提供了很多有用的方法,例如:
getYears():获取Period实例中的年份差
getMonths():获取Period实例中的月份差
getDays():获取Period实例中的天数差
plusYears(long yearsToAdd):将指定的年数添加到该Period实例
plusMonths(long monthsToAdd):将指定的月数添加到该Period实例
plusDays(long daysToAdd):将指定的天数添加到该Period实例


7、java.time.ZonedDateTime:表示带时区的日期时间信息,ZonedDateTime类提供了很多有用的方法,例如:
getYear():获取年份
getMonth():获取月份
getDayOfMonth():获取月中的日期
getHour():获取小时数
getMinute():获取分钟数
getSecond():获取秒数
withZoneSameInstant(ZoneId zone):将时区调整为指定的时区,并以UTC时间表示
withZoneSameLocal(ZoneId zone):将时区调整为指定的时区,并以本地时间表示
plus(Duration amountToAdd):将指定的持续时间添加到该ZonedDateTime实例


8、java.time.DateTimeFormatter:用于格式化和解析日期时间信息,DateTimeFormatter类提供了很多有用的方法,例如:
ofLocalizedDate(FormatStyle dateStyle):获取指定格式样式的本地日期格式化器
ofLocalizedTime(FormatStyle timeStyle):获取指定格式样式的本地时间格式化器
ofLocalizedDateTime(FormatStyle dateTimeStyle):获取指定格式样式的本地日期时间格式化器
parse(CharSequence text, TemporalQuery query):将指定的日期时间字符串解析为指定类型的Temporal对象
parse(CharSequence text):将指定的日期时间字符串解析为LocalDateTime对象
另外,DateTimeFormatter还支持一些预定义的日期时间格式模板,例如:
"yyyy-MM-dd":代表年-月-日的格式
"HH:mm:ss":代表小时:分钟:秒的格式
"yyyy-MM-dd HH:mm:ss":代表年-月-日 小时:分钟:秒的格式

新旧时间的构造样例:

    @Test
    public void dateUseTest() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        Date calendarTime = calendar.getTime();

        System.out.println("=============================旧的日期=============================");
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("使用Date构造日期:" + simpleDate.format(date));
        System.out.println("使用Calendar构造日期:" + simpleDate.format(calendarTime));

        System.out.println("=============================旧的时间=============================");
        SimpleDateFormat simpleTime = new SimpleDateFormat("HH:mm:ss");
        System.out.println("使用Date构造时间:" + simpleTime.format(date));
        System.out.println("使用Calendar构造时间:" + simpleTime.format(calendarTime));

        System.out.println("=============================旧的日期和时间=============================");
        SimpleDateFormat simpleDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("使用Date构造日期和时间:" + simpleDateTime.format(date));
        System.out.println("使用Calendar构造日期和时间:" + simpleDateTime.format(calendarTime));

        System.out.println("=============================新的日期=============================");
        LocalDate ofDate = LocalDate.of(2019, 5, 12);
        LocalDate nDate = LocalDate.now();
        System.out.println("使用LocalDate.of构造日期:" + ofDate);
        System.out.println("使用LocalDate.now构造日期:" + nDate);

        System.out.println("=============================新的时间=============================");
        LocalTime ofTime = LocalTime.of(15, 01, 30);
        LocalTime time = LocalTime.now();
        System.out.println("使用LocalTime.of构造日期和时间:" + ofTime);
        System.out.println("使用LocalTime.now构造日期和时间:" + time);

        System.out.println("=============================新的日期和时间=============================");
        LocalDateTime ofDateTime = LocalDateTime.of(2019, 5, 12, 15, 01, 30);
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("使用LocalDateTime.of构造日期和时间:" + ofDateTime);
        System.out.println("使用LocalDateTime.now构造日期和时间:" + dateTime);

        System.out.println("=============================新的日期和时间格式化=============================");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("使用DateTimeFormatter格式化日期和时间:" + dateTime.format(formatter));
    }

新旧时间的内容获取样例:

    @Test
    public void dateGetTest() {
        System.out.println("=============================旧的方式获取日期时间信息=============================");
        Calendar calendar = Calendar.getInstance();
        System.out.println("使用Calendar获取年:" + calendar.get(Calendar.YEAR));
        //月是从0开始
        System.out.println("使用Calendar获取月:" + String.valueOf(calendar.get(Calendar.MONTH) + 1));
        System.out.println("使用Calendar获取日:" + calendar.get(Calendar.DAY_OF_MONTH));
        //获得星期几(注意(这个与Date类是不同的):1代表星期日、2代表星期一、3代表星期二,以此类推)
        System.out.println("使用Calendar获取星期几:" + calendar.get(Calendar.DAY_OF_WEEK));
        System.out.println("使用Calendar获取时:" + calendar.get(Calendar.HOUR_OF_DAY));
        System.out.println("使用Calendar获取分:" + calendar.get(Calendar.MINUTE));
        System.out.println("使用Calendar获取秒:" + calendar.get(Calendar.SECOND));

        System.out.println("=============================新的方式获取日期时间信息=============================");
        //LocalDate和LocalTime同样有类似的方法,这里以LocalDateTime为例
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("使用LocalDateTime获取年:" + dateTime.getYear());
        System.out.println("使用LocalDateTime获取月:" + dateTime.getMonthValue());
        System.out.println("使用LocalDateTime获取日:" + dateTime.getDayOfMonth());
        System.out.println("使用LocalDateTime获取时:" + dateTime.getHour());
        System.out.println("使用LocalDateTime获取分:" + dateTime.getMinute());
        System.out.println("使用LocalDateTime获取秒:" + dateTime.getSecond());
    }

新旧时间的运算样例:

    @Test
    public void dateCalculateTest() {
        System.out.println("=============================旧的方式获取日期时间信息=============================");
        Calendar calendar = Calendar.getInstance();
        System.out.println("当前Calendar获取到的日期信息" + calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.DAY_OF_MONTH) + "日" + calendar.get(Calendar.HOUR_OF_DAY) + "时");
        //加5天
        calendar.add(Calendar.DAY_OF_MONTH, 5);
        //减2年
        calendar.add(Calendar.YEAR, -2);
        //减1小时
        calendar.add(Calendar.HOUR_OF_DAY, -1);
        System.out.println("运算后Calendar获取到的日期信息" + calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.DAY_OF_MONTH) + "日" + calendar.get(Calendar.HOUR_OF_DAY) + "时");

        System.out.println("=============================新的方式获取日期时间信息=============================");
        //LocalDate和LocalTime同样有类似的方法,这里以LocalDateTime为例
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println("当前LocalDateTime获取到的日期信息" + dateTime.getYear() + "年" + dateTime.getDayOfMonth() + "日" + dateTime.getHour() + "时");
        //加10天
        dateTime = dateTime.plusDays(10);
        //减一年
        dateTime = dateTime.minusYears(1);
        //减两小时
        dateTime = dateTime.minusHours(2);
        System.out.println("运算后LocalDateTime获取到的日期信息" + dateTime.getYear() + "年" + dateTime.getDayOfMonth() + "日" + dateTime.getHour() + "时");

        System.out.println("=============================新的方式计算日期时间的差值=============================");
        //旧的日期时间没有现成的api去计算,需要自己去实现
        LocalDate lDate1 = LocalDate.of(2019, 1, 1);
        LocalDate lDate2 = LocalDate.now();
        Period period1 = Period.between(lDate1, lDate2);
        System.out.println("使用Period计算时间差为:" + period1.getYears() + "年" + period1.getMonths() + "月" + period1.getDays() + "天");
        Period period2 = period1.plusYears(1).plusMonths(2).plusDays(3);
        System.out.println("使用Period加上1年2月3天后的时间差为:" + period2.getYears() + "年" + period2.getMonths() + "月" + period2.getDays() + "天");

        LocalDateTime lDateTime1 = LocalDateTime.of(2019, 1, 1, 0, 0, 0);
        LocalDateTime lDateTime2 = LocalDateTime.now();
        Duration duration1 = Duration.between(lDateTime1, lDateTime2);
        System.out.println("使用Duration计算的时间差为:" + duration1.getSeconds() + "秒");
        System.out.println("使用Duration计算的时间差为:" + duration1.toDays() + "天");
        Duration duration2 = duration1.plusHours(2).plusMinutes(30).plusSeconds(10);
        System.out.println("使用Duration加上2小时30分10秒后的时间差为:" + duration2.getSeconds() + "秒");

        System.out.println("=============================新的方式调整日期时间=============================");
        LocalDate date = LocalDate.parse("2019-01-01");
        LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("使用TemporalAdjusters调整后该月的第一天为:" + firstDay);
        System.out.println("使用TemporalAdjusters调整后该月的最后一天为:" + lastDay);
        LocalDate nextSunday = date.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        System.out.println("使用TemporalAdjusters调整后下一个周日为:" + nextSunday);

        System.out.println("=============================新的方式带时区的日期时间=============================");
        ZonedDateTime zdt = ZonedDateTime.of(2019, 5, 14, 12, 0, 0, 0, ZoneId.of("Asia/Shanghai"));
        System.out.println("北京时间:" + zdt);
        System.out.println("年份:" + zdt.getYear());
        System.out.println("月份:" + zdt.getMonthValue());
        System.out.println("日期:" + zdt.getDayOfMonth());
        System.out.println("小时数:" + zdt.getHour());
        System.out.println("分钟数:" + zdt.getMinute());
        System.out.println("秒数:" + zdt.getSecond());
        ZonedDateTime zdt2 = zdt.withZoneSameInstant(ZoneId.of("UTC"));
        System.out.println("调整时区后的UTC时间:" + zdt2);
        ZonedDateTime zdt3 = zdt.plus(Duration.ofHours(5));
        System.out.println("加上5小时后的时间:" + zdt3);
    }

新旧时间的转换样例:

    @Test
    public void convertTest() {
        System.out.println("=============================将Date转换为Instant、LocalDateTime等类型=============================");
        Date date = new Date();
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println("使用instant.atZone转换成LocalDateTime:" + localDateTime);
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
        System.out.println("使用instant.atZone转换成ZonedDateTime:" + zonedDateTime);

        localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println("使用LocalDateTime.ofInstant转换成LocalDateTime:" + localDateTime);
        zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println("使用ZonedDateTime.ofInstant转换成ZonedDateTime:" + zonedDateTime);

        Calendar calendar = Calendar.getInstance();
        instant = calendar.toInstant();
        localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println("使用LocalDateTime.ofInstant转换成LocalDateTime:" + localDateTime);
        zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        System.out.println("使用ZonedDateTime.ofInstant转换成ZonedDateTime:" + zonedDateTime);

        System.out.println("=============================将Instant、LocalDateTime等类型转换为Date=============================");
        LocalDateTime nowDateTime = LocalDateTime.now();
        Instant instant1 = nowDateTime.atZone(ZoneId.systemDefault()).toInstant();
        Date date1 = new Date(instant1.toEpochMilli());
        System.out.println("使用new Date转换成Date:" + date1);
        Date date2 = Date.from(instant1);
        System.out.println("使用Date.from转换成Date:" + date2);

        System.out.println("=============================将LocalDate、LocalTime和LocalDateTime转换为Date=============================");
        LocalDate nowDate = LocalDate.now();
        Instant instant2 = nowDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        Date date3 = Date.from(instant2);
        System.out.println("使用Date.from转换成Date:" + date3);

        LocalTime nowTime = LocalTime.now();
        nowDate = LocalDate.now();
        Instant instant3 = LocalDateTime.of(nowDate, nowTime).atZone(ZoneId.systemDefault()).toInstant();
        Date date4 = Date.from(instant3);
        System.out.println("使用Date.from转换成Date:" + date4);

        localDateTime = LocalDateTime.now();
        Instant instant4 = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        Date date5 = Date.from(instant4);
        System.out.println("使用Date.from转换成Date:" + date5);

        System.out.println("=============================将Calendar转换为Instant、LocalDateTime等类型=============================");
        calendar = Calendar.getInstance();
        Date date6 = calendar.getTime();
        Instant instant5 = date6.toInstant();
        LocalDateTime nowTime1 = LocalDateTime.ofInstant(instant5, ZoneId.systemDefault());
        System.out.println("使用LocalDateTime.ofInstant转换成LocalDateTime:" + nowTime1);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值