ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java 日期时间使用总结

2022-01-11 17:04:09  阅读:131  来源: 互联网

标签:总结 Java System Date 日期 LocalDateTime println public out


Java 中有关日期时间的操作,其实非常简单,没什么好介绍的。之所以编写简单知识点的博客,主要还是因为最近比较忙碌。但是不管多么忙碌,自己还是想挤出时间,保持编写技术博客的习惯。毕竟编写博客,不仅仅是为了总结,向别人分享技术,更重要的是锻炼自己的思考沉淀能力,以及写作表达能力。下面我就快速简单的介绍一下 Java 中的日期时间操作类吧。


一、传统的日期时间类

传统的日期时间操作类,主要有两个:Date 类和 SimpleDateFormat 类。

Date 类代码示例:

import java.util.Date;

public class DateDemo {
    public static void main(String[] args) {

        //使用空参构造 Date 对象,打印出的时间就是本机系统当前时间
        Date date1 = new Date();
        System.out.println(date1);

        /*
        使用有参构造 Date 对象,参数传递的是从计算机原点时间起的毫秒值
        在零时区,计算机原点时间是 1970 年 1 月 1 日 0 点整
        因为中国在东八区,所以对于中国而言,计算机原点时间是  1970 年 1 月 1 日 8 点整。
        传递 0 毫秒,表示获取计算机原点时间
        */
        Date date2 = new Date(0L);
        //打印出来的是 Thu Jan 01 08:00:00 CST 1970
        //也就是1970年1月1日8点,主要是因为中国是东八区,因此需要加8个小时
        System.out.println(date2);

        Date date3 = new Date();
        //通过 Date 对象的 getTime 可以获取到从计算机原点时间累计到现在的毫秒值
        long time1 = date3.getTime();
        System.out.println(time1);

        //Java也提供了一个快捷方法,获取到从计算机原点时间累计到现在的毫秒值
        long time2 = System.currentTimeMillis();
        //打印出来的 time2 和 time1 的值是相同的
        System.out.println(time2); 

        Date date4 = new Date();
        //通过 setTime 传入从计算机原点起累计的毫秒值,可以设置出新的时间
        date4.setTime(0L);
        System.out.println(date4); //此时打印出的是计算机原点时间
    }
}


SimpleDateFormat 类的代码演示:
import java.text.SimpleDateFormat;
import java.util.Date;

/*
SimpleDateFormat 主要是为了将 Date 对象格式化为自定义的日期时间字符串
也可以将指定格式的日期格式字符串,解析为 Date 对象
*/
public class DateDemo {
    public static void main(String[] args) {
        //将【日期对象】转换为【字符串】代码示例
        Date date1 = new Date();
        //创建了一个日期格式。
        //SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String result = sdf1.format(date1);
        System.out.println(result);

        //将【字符串】转为【日期对象】代码示例
        String str = "2012-12-12 12:12:12";
        //SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

        Date date2 = null;
        try {
            date2 = sdf2.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println(date2);
    }
}

Date 类的实例也有很多方法,这里就不演示了,大家可以自己进行学习研究,主要是因为目前 Date 类已经被使用的越来越少了,因为在 JDK8 以后有更好的 LocalDateTime 可以使用,我们重点介绍 LocalDateTime 的使用。


二、JDK8以后新增的日期时间类

类名 说明
LocalDate 表示日期(年月日)
LocalTime 表示时间(时分秒)
LocalDateTime 表示时间日期 (年月日时分秒)
DateTimeFormatter 将日期时间格式化为字符串或解析日期字符串
Period 表示日期间隔 (间隔的年数,月数,天数,总月数)
Duration 表示时间间隔 (间隔的秒数,毫秒数,纳秒数)

对于 LocalDate 、 LocalTime 、LocalDateTime 这三个类来说,最常用的还是 LocalDateTime ,下面我们就以 LocalDateTime 为例进行代码演示:

import java.time.LocalDateTime;

public class LocalDateTimeDemo {
    public static void main(String[] args) {
        //实例化 LocalDateTime 对象
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now); //打印系统本机当前时间

        //采用 of 的重载方法,按照指定的年月日时分秒实例化 LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.of(2022, 12, 12, 11, 11, 11);
        System.out.println(localDateTime);
    }
}

LocalDateTime 常用方法为下表,由于见名知意,非常简单,这里就不再演示了。

方法名 说明
public int getYear() 获取年
public int getMonthValue() 获取月份(1-12)
public int getDayOfMonth() 获取月份中的第几天(1-31)
public int getDayOfYear() 获取一年中的第几天(1-366)
public DayOfWeek getDayOfWeek() 获取星期
public int getMinute() 获取分钟(0 - 59)
public int getHour() 获取小时(0 - 23)
public int getSecond() 获取秒(0 - 59)

LocalDateTime 通过 DateTimeFormatter 与日期时间格式的字符串之间的转换代码演示如下:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeDemo {
    public static void main(String[] args) {
        //将字符串转为为 LocalDateTime
        String str1 = "2022-11-11 12:13:15";
        DateTimeFormatter pattern1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(str1, pattern1);
        System.out.println(parse);

        //将 LocalDateTime 转为为字符串
        LocalDateTime localDateTime = LocalDateTime.of(2022, 12, 12, 23, 59, 59);
        System.out.println(localDateTime);

        DateTimeFormatter pattern2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
        String str2 = localDateTime.format(pattern2);
        System.out.println(str2);
    }
}

LocalDateTime 进行日期加减的方法,对于以 plus 为开头的方法来说,传入正数为添加,传入负数为减去。

方法名 说明
public LocalDateTime plusYears (long years) 添加或者减去年
public LocalDateTime plusMonths(long months) 添加或者减去月
public LocalDateTime plusDays(long days) 添加或者减去日
public LocalDateTime plusHours(long hours) 添加或者减去时
public LocalDateTime plusMinutes(long minutes) 添加或者减去分
public LocalDateTime plusSeconds(long seconds) 添加或者减去秒
public LocalDateTime plusWeeks(long weeks) 添加或者减去周

LocalDateTime 修改对应的日期时间的方法如下表,也是见名知意,非常简单,这里就不演示了。

方法名 说明
public LocalDateTime withYear(int year) 直接修改年
public LocalDateTime withMonth(int month) 直接修改月
public LocalDateTime withDayOfMonth(int dayofmonth) 直接修改日期(一个月中的第几天)
public LocalDateTime withDayOfYear(int dayOfYear) 直接修改日期(一年中的第几天)
public LocalDateTime withHour(int hour) 直接修改小时
public LocalDateTime withMinute(int minute) 直接修改分钟
public LocalDateTime withSecond(int second) 直接修改秒


Period 类主要用于计算两个 LocalDate 的间隔,主要方法如下:
方法名 说明
public static Period between(开始时间,结束时间) 计算两个日期的间隔
public int getYears() 获得这段时间的年数
public int getMonths() 获得此期间的总月数
public int getDays() 获得此期间的天数
public long toTotalMonths() 获取此期间的总月数

演示代码如下:

import java.time.LocalDate;
import java.time.Period;

public class PeriodDemo {
    public static void main(String[] args) {
        //计算两个日期之间的间隔,需要使用 LocalDate 对象
        LocalDate localDate1 = LocalDate.of(2022, 1, 1);
        LocalDate localDate2 = LocalDate.of(2050, 12, 12);
        Period period = Period.between(localDate1, localDate2);
        System.out.println(period);//P28Y11M11D

        //获得间隔的年数
        System.out.println(period.getYears());//28
        //获得间隔的月数
        System.out.println(period.getMonths());//11
        //获得间隔的天数
        System.out.println(period.getDays());//11
        //获取间隔的总月数
        System.out.println(period.toTotalMonths());//347

        /*
        从以上打印出来的结果可以发现,以 get 开头的方法,获取间隔的年数,月数,天数,并不是总数。
        其实就是对应年之间,对应月之间,对应天之间的相减,这一点需要特别注意
        以 to 开头的方法,获取的才是间隔的总数,但是 period 只有 toTotalMonths 这一个方法,
        要是有 toTotalDays 和 toTotalYears 方法就更好了。
        */
    }
}


Duration 类主要用于计算两个 LocalDate 或 LocalDateTime 之间的间隔,主要方法如下:
方法名 说明
public static Durationbetween(开始时间,结束时间) 计算两个日期时间的间隔
public long toDays() 获得此时间间隔的总天数
public long toHours() 获得此时间间隔的总小时数
public long toMinutes() 获得此时间间隔的总分钟数
public long toSeconds() 获得此时间间隔的总秒数
public long toMillis() 获得此时间间隔的总毫秒数
public long toNanos() 获得此时间间隔的总纳秒数

演示代码如下:

import java.time.Duration;
import java.time.LocalDateTime;

public class DurationDemo {
    public static void main(String[] args) {
        LocalDateTime localDateTime1 = LocalDateTime.of(2021, 1, 1, 12, 12, 12);
        LocalDateTime localDateTime2 = LocalDateTime.of(2022, 2, 1, 12, 12, 12);
        Duration duration = Duration.between(localDateTime1, localDateTime2);
        System.out.println(duration);//PT9504H

        //获得间隔的总天数
        System.out.println(duration.toDays());
        //获得间隔的总小时数
        System.out.println(duration.toHours());
        //获得间隔的总分钟数
        System.out.println(duration.toMinutes());
        //获得间隔的总秒数
        System.out.println(duration.toSeconds());//34214400
        //获得间隔的总毫秒数
        System.out.println(duration.toMillis());//34214400000
        //获得间隔的总纳秒数
        System.out.println(duration.toNanos());//34214400000000000

        /*
        从上面的输出结果可以发现,以 to 开头的方法,获取的都是对应的间隔总数
        这些方法的实现结果,是我们经常需要用到的
        */
    }
}

到此为止,Java 有关日期时间的操作,已经基本介绍完了。总体来说非常简单,我在这里列出的都是比较常用的方法,至于其它方法的使用,需要用到的时候,查一下 Jdk 文档或者上网查找一下相关资料即可,总之都是非常简单。



标签:总结,Java,System,Date,日期,LocalDateTime,println,public,out
来源: https://www.cnblogs.com/studyjobs/p/15789079.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有