Java时间类Date、Calender 、LocalDateTime总结
代码环境:
java version “11.0.14” 2022-01-18 LTS
IntelliJ IDEA 2020.3 (Ultimate Edition)
Windows 10 企业版 LTSC 21H2 19044.1706
一、Date类
1、无参构造方法
Date 类的无参构造函数所创建的对象可以获取本机当前时间,例如:
Date date = new Date();//Date类在java.util包中
System.out.println(date);//输出当前时间
[^Fri Jun 10 19:35:23 CST 2022]: Date 对象表示时间的默认顺序为:星期、月、日、小时、分、秒、年。
2、有参构造方法
计算机系统自身时间是1970年1月1日0时,也就是格林威治时间,可以根据这个时间使用 Date 有参的构造方法创建 Date 对象。例如:
Date date1 = new Date(1000);
Date date2 = new Date(-1000);
[^Thu Jan 01 08:00:01 CST 1970]:
[^Thu Jan 01 07:59:59 CST 1970]:
Date 类有如下两个构造方法:
-
Date(): 使用该构造方法创建的对象可以获取本地的当前时间。
-
Date(long date):此种形式表示从 GMT 时间(格林尼治时间)1970 年 1 月 1 日 0 时 0 分 0 秒开始经过参数 date 指定的毫秒数。
方法 | 描述 |
---|---|
boolean after(Date when) | 判断此日期是否在指定日期之后 |
boolean before(Date when) | 判断此日期是否在指定日期之前 |
int compareTo(Date anotherDate) | 比较两个日期的顺序 |
boolean equals(Object obj) | 比较两个日期的相等性 |
long getTime() | 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来,此 Date 对象表示的毫秒数 |
String toString() | String: dow mon dd hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat)。 |
日期比较
- 使用 getTime() 方法获取两个日期(自1970年1月1日经历的毫秒数值),然后比较这两个值。
- 使用方法 before(),after() 和 equals()。例如,一个月的12号比18号早,则 new Date(99, 2, 12).before(new Date (99, 2, 18)) 返回true。
- 使用 compareTo() 方法,它是由 Comparable 接口定义的,Date 类实现了这个接口。
格式化时间
这里只使用最常用的
Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(date));
二、Calender类
Date类和Calendar类都是关于日期的类,都在java.util包中,使用时需要import。
Calendar提供了获取或设置各种日历字段的方法。是抽象的,无法实例化
构造方法:protected Calendar :由于修饰词是 protected ,无法直接创建对象。
方法名 | 说明 |
---|---|
static Calendar getInstance() | 使用默认时区和区域获取日历。 |
void set(int year , int month , int date , int hourofday , int second) | 设置日历的年月日时分。 |
int get(int field) | 返回给日历字段的值。如年、月、日等 |
void setTime(Date date) | 用给定的Date设置日历的时间。Date-Calendar |
Date getTime() | 返回一个Date表示此日历的时间。Calendar-Date |
void add(int field , int amount) | 按照日历的规则,给指定的字段添加或减少时间 |
long getTimeMillies() | 毫秒为单位返回该日历的时间。 |
格式化时间
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
// getTime() 转化为Date格式去转换
System.out.println(calendar.getTime());
三、LocalDateTime类
LocalDate:只含年月日的日期对象
LocalTime:只含时分秒的时间对象
LocalDateTime:同时含有年月日时分秒的日期对象
LocalDate - 初始化
1. now(): 给出LocalDate实例,该实例包含默认时区的系统时钟的当前日期。
2. now(Clock clock): 提供LocalDate实例,该实例具有从指定时钟获得的当前日期。
3. now(ZoneId zone): 给出当前日期的LocalDate
实例,该日期来自指定时区的系统时钟
4. of(int year, int month, int dayOfMonth: 从给定的年、月、日中获得LocalDate
实例,输入数据类型为int
。
5. of(int year, Month month, int dayOfMonth): 从给定的年(int
)、月(Month
)和日(int
)给出LocalDate
实例。