日期时间类

1. Calendar

  • Date类的API大部分被废弃了,替换为Calendar(日历)。
  • Calendar 类是一个抽象类,主用用于完成日期字段之间相互操作的功能。

实例化

  • 使用Calendar.getInstance()方法
  • 调用它的子类GregorianCalendar(公历)的构造器。

常用方法

  • public int get(int field):返回给定日历字段的值
  • public void set(int field,int value) :将给定的日历字段设置为指定的值
  • public void add(int field,int amount):根据日历的规则,为给定的日历字段添加或者减去指定的时间量
  • public final Date getTime():将Calendar转成Date对象
  • public final void setTime(Date date):使用指定的Date对象重置Calendar的时间

常用字段

字段值 含义
YEAR
MONTH 月(从0开始,可以+1使用)
DAY_OF_MONTH 一月中的天数
HOUR 时(12小时制)
HOUR_OF_DAY 时(24小时制)
MINUTE 分钟
SECOND 秒钟
DAY_OF_WEEK 一周中的天数(周日为1,可以 -1使用)

2. DateTimeFormatter

该类提供了三种格式化方法:

  • 预定义的标准格式。如:ISO_LOCAL_DATE_TIMEISO_LOCAL_DATEISO_LOCAL_TIME

  • 本地化相关的格式。如:ofLocalizedDate(FormatStyle.LONG)

    // 本地化相关的格式。如:ofLocalizedDateTime()
    // FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime

    // 本地化相关的格式。如:ofLocalizedDate()
    // FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
  • 自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)

ofPattern(String pattern) 静态方法,返回一个指定字符串格式的DateTimeFormatter
format(TemporalAccessor t) 格式化一个日期、时间,返回字符串
parse(CharSequence text) 将指定格式的字符序列解析为一个日期、时间
import org.junit.Test;

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

public class TestDatetimeFormatter {
@Test
public void test1(){
// 方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
// 格式化:日期-->字符串
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter.format(localDateTime);
System.out.println(localDateTime);
System.out.println(str1);//2022-12-04T21:02:14.808

// 解析:字符串 -->日期
TemporalAccessor parse = formatter.parse("2022-12-04T21:02:14.808");
LocalDateTime dateTime = LocalDateTime.from(parse);
System.out.println(dateTime);
}

@Test
public void test2(){
LocalDateTime localDateTime = LocalDateTime.now();
// 方式二:
// 本地化相关的格式。如:ofLocalizedDateTime()
// FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);

// 格式化
String str2 = formatter1.format(localDateTime);
System.out.println(str2);// 2022年12月4日 下午09时03分55秒

// 本地化相关的格式。如:ofLocalizedDate()
// FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
// 格式化
String str3 = formatter2.format(LocalDate.now());
System.out.println(str3);// 2022年12月4日 星期日
}

@Test
public void test3(){
//方式三:自定义的方式(关注、重点)
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
//格式化
String strDateTime = dateTimeFormatter.format(LocalDateTime.now());
System.out.println(strDateTime); //2022/12/04 21:05:42
//解析
TemporalAccessor accessor = dateTimeFormatter.parse("2022/12/04 21:05:42");
LocalDateTime localDateTime = LocalDateTime.from(accessor);
System.out.println(localDateTime); //2022-12-04T21:05:42
}
}

3. Instant

  • 时间线上的一个瞬时点。 这可能被用来记录应用程序中的事件时间戳。
  • 时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

实例化

  • static Instant now():静态方法,返回默认UTC时区的Instant类的对象。
  • static Instant ofEpochMilli(long epochMilli):静态方法,返回在1970-01-01 00:00:00基础上加上指定毫秒数之后的Instant类的对象。

常用方法

  • OffsetDateTime atOffset(ZoneOffset offset) :结合即时的偏移来创建一个 OffsetDateTime。
  • long toEpochMilli() :返回1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳。
  • long getEpochSecond():获得当前时间戳(以秒为单位)。
  • long getNano():获得当前时间戳(以纳秒为单位)。

4. java.util.Date

构造器

  • Date():使用无参构造器创建的对象可以获取本地当前时间
  • Date(long):以指定的毫秒值换算成日期时间对象。

常用方法

  • long getTime():返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
  • void setTime(long):设置自 1970 年 1 月 1 日 00:00:00 GMT 以指定毫秒数表示的对象。
  • String toString():把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat),zzz是时间标准。
  • Instant toInstant():将Date对象转化成表示时间点的Instant对象。
  • static Date from(Instant):将Instant对象转化成表示日期的Date对象。

5. java.sql.Date

java.sql.Date是继承于ava.util.Date的子类

构造器

  • Date(long):以指定的毫秒值换算成日期时间对象。

常用方法

  • long getTime():返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
  • void setTime(long):设置自 1970 年 1 月 1 日 00:00:00 GMT 以指定毫秒数表示的对象。
  • String toString():把此 Date 对象转换为以下形式的 String: yyyy-MM-ss
  • Instant toInstant():将Date对象转化成表示时间点的Instant对象。
  • static Date from(Instant):将Instant对象转化成表示日期的Date对象。

6. LocalDate、LocalTime、LocalDateTime

  • 构造器为private,需要调用其他方法实例化。
  • 不可变性,修改会返回新的日期时间对象。

实例化

  • static Xxx now() / now(ZoneId zone) :静态方法,根据当前时间创建对象/指定时区的对象。
  • static Xxx of(xx,xx,xx,xx,xx,xxx) : 静态方法,根据指定日期/时间创建对象。

常用方法

  • int getDayOfYear() | Xxx withDayOfYear(int)
  • int getDayOfMonth() | Xxx withDayOfMonth(int)
  • int getDayOfWeek()
  • int getYear() | Xxx withYear(int)
  • Month getMonth() | Xxx withMonth(int)
  • int getMonthValue()
  • int getHours()
  • int getMinute()
  • int getSecond()
  • Xxx with(TemporalAdjuster t)
  • Xxx plusYears(long) | Xxx minusYears(long)
  • Xxx plusMonths(long) | Xxx minusMonths(long)
  • Xxx plusWeeks(long) | Xxx minusWeeks(long)
  • Xxx plusDays(long) | Xxx minusDays(long)
  • Xxx plusHours(long) | Xxx minusHours(long)
  • Xxx plus(TemporalAmount t) | Xxx minus(TemporalAmount t)
  • boolean isBefore() | boolean isAfter():比较两个 LocalDate。
  • boolean isLeapYear():判断是否是闰年(在LocalDate类中声明)。
  • String format(DateTimeFormatter t):格式化本地日期、时间,返回一个字符串。
  • Xxx parse(Charsequence text):将指定格式的字符串解析为日期、时间。

7. SimpleDateFormat

  • java.text.SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类。
  • 可以进行格式化:日期 —-> 文本
  • 可以进行解析:文本 —-> 日期

构造器

  • public SimpleDateFormat() :默认的模式和语言环境创建对象。
  • public SimpleDateFormat(String pattern):该构造方法可以用参数pattern指定的格式创建一个对象。

常用方法

  • public String format(Date date):方法格式化时间对象date。(格式化)
  • public Date parse(String source):从给定字符串的开始解析文本,以生成一个日期。(解析)
//格式化
@Test
public void test1(){
Date d = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E Z");
//把Date日期转成字符串,按照指定的格式转
String str = sf.format(d);
System.out.println(str);////2024年10月08日 16时45分56秒 483毫秒 周二 +0800
}

//解析
@Test
public void test2() throws ParseException{
String str = "2024年10月08日 16时45分56秒 483毫秒 周二 +0800";
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 SSS毫秒 E Z");
Date d = sf.parse(str);
System.out.println(d);//Tue Oct 08 16:45:56 CST 2024
}
Letter Date or Time Component Presentation Examples
G Era designator 文本 AD
y 一年 年份 1996; 96
Y 一周一年 年份 2009; 09
M 一年中的月份(上下文敏感) 月份 July; Jul; 07
L 一年中的月份(独立格式) 月份 July; Jul; 07
w 一年中的周数 数值 27
W 一月中的周数 数值 2
D 一年中的天数 数值 189
d 一月中的天数 数值 10
F 一月中的周数 数值 2
E 一周中的星期名称 文本 Tuesday; Tue
u 一周中的星期 数值 1
a AM / PM标记 文本 PM
H 一天中的小时数(0 - 23) 数值 0
k 一天中的小时数(1 - 24) 数值 24
K 半天中的小时数(1 - 24) 数值 0
h 半天中的小时数(1 - 24) 数值 12
m 一小时中的分钟数 数值 30
s 一分钟中的秒钟数 数值 55
S 一秒钟中的毫秒钟数 数值 978
z 时区 一般时区 Pacific Standard Time; PST; GMT-08:00
Z 时区 RFC 822 时区 -0800
X 时区 ISO 8601 时区 -08; -0800; -08:00