Date

Date

构造器:

  • Date():获取当前时间的毫秒值作为对象返回;
  • Date(long date):根据传入的时间毫秒值,返回 Date 对象;

其他构造器已弃用,指定年月日等参数的构造请参考 Calendar 类
方法:

  • long getTime() :返回由该 Date 对象表示的自 1970年1月1日00:00:00 GMT 以来的毫秒数。
  • boolean after(Date when):判断此时间是否在指定时间之后;
  • boolean before(Date when):判断此时间是否在指定时间之前;

    DateFormat

  • 把 Date 时间类型对象转化成指定格式的字符串;

  • 把指定格式的字符串时间转化成 Date 类型对象;
  • DateFormat 是一个抽象类,一般使用它的子类 SimpleDateFormat 类来实现

方法:

方法 解释说明
public String format(Date date) 返回将 date 转化为指定格式的字符串
public String format(Object date) 返回时间毫秒值 date 转化为指定格式的字符串
public Date parse(String source) 将指定格式的字符串时间转化为 Date 对象并返回
  1. //把时间对象转成字符串
  2. DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  3. Date date = new Date();
  4. long time = date.getTime();
  5. String timeStr = df.format(time);
  6. String str = df.format(date);
  7. //把字符串装成时间对象
  8. Date date = df.parse("2019-9-9 11:11:11"); //需要捕获异常

其他格式化字符:SimpleDateFormat

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year (context sensitive) Month July; Jul; 07
L Month in year (standalone form) Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week Number 1 (1 = Monday, …, 7 = Sunday)
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00

Calendar

  • Calendar 是一个抽象类,获取实例的方式是调用 getInstance() 方法;

Calendar的方法:
1. public static Calendar getInstance(): 返回一个日历类的对象。
2. public int get(int field):取日期中的某个字段信息。
3. public void set(int field,int value):修改日历的某个字段信息。
4. public void add(int field,int amount):为某个字段增加/减少指定的值
5. public final Date getTime(): 拿到此刻日期对象。
6. public long getTimeInMillis(): 拿到此刻时间毫秒值

public class CalendarDemo {
    public static void main(String[] args) {
        // 1.通过调用日历类的静态方法getInstance得到一个当前此刻日期对象对应的日历对象。
        Calendar rightNow = Calendar.getInstance();
        System.out.println(rightNow);

        // 2.获取年:
        int year = rightNow.get(Calendar.YEAR);
        System.out.println(year);

        int mm = rightNow.get(Calendar.MONTH) + 1;
        System.out.println(mm);

        // 3.一年中的第几天: 308
        int days = rightNow.get(Calendar.DAY_OF_YEAR);
        System.out.println(days);

        // 4.修改日历的信息
        //rightNow.set(Calendar.YEAR , 2099);
        //System.out.println(rightNow.get(Calendar.YEAR));

        // 5.日历可以得到此刻日期对象。
        Date d = rightNow.getTime();
        System.out.println(d);

        // 6.此刻时间毫秒值
        long time = rightNow.getTimeInMillis();
        System.out.println(time);

        // 7.请问701天  15小时后是哪个日期
        // 让日历的一年中的第几天往后走 701天!
        rightNow.add(Calendar.DAY_OF_YEAR , 701);
        rightNow.add(Calendar.HOUR , 15);
        long time1 = rightNow.getTimeInMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss EEE a");
        System.out.println(sdf.format(time1));
    }
}

Java 8 时间日期 API

旧版的 Java 中,日期时间 API 存在的问题:

  • 非线程安全− java.util.Date 是非线程安全的,所有的日期类都是可变的,这是 Java 日期类最大的问题之一。
  • 设计很差− Java 的日期/时间类的定义并不一致,在 java.util 和 java.sql 的包中都有日期类,此外用于格式化和解析的类在 java.text 包中定义。java.util.Date 同时包含日期和时间,而 java.sql.Date 仅包含日期,将其纳入 java.sql 包并不合理。另外这两个类都有相同的名字,这本身就是一个非常糟糕的设计。
  • 时区处理麻烦− 日期类并不提供国际化,没有时区支持,因此 Java引入 了 java.util.Calendar 和 java.util.TimeZone类,但他们同样存在上述所有的问题。

Java 8 在 java.time 包下提供了很多新的 API。以下为两个比较重要的 API:

  • 本地日期和时间:LocalDateTime,LocalDate,LocalTime;
  • 带时区的日期和时间:ZonedDateTime;
  • 时刻:Instant;
  • 时区:ZoneId,ZoneOffset;
  • 时间间隔:Duration;
  • 格式化类型:DateTimeFormatter;

    LocalDateTime

    表示一个本地时间和日期。 ```java LocalDate d = LocalDate.now(); // 当前日期 LocalTime t = LocalTime.now(); // 当前时间 LocalDateTime dt = LocalDateTime.now(); // 当前日期和时间

d = dt.toLocalDate(); t = dt.toLocalTime();

<a name="qriNw"></a>
### of() 方法
```java
public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) {
    LocalDate date = LocalDate.of(year, month, dayOfMonth);
    LocalTime time = LocalTime.of(hour, minute, second);
    return new LocalDateTime(date, time);
}

获取年月日时分秒等信息

image.png

日期时间加减

image.png

替换日期时间字段

image.png
例如,withYear:将日期中的年份替换成参数中指定的整数值;

public static void main(String[] args) {
    LocalDate localDate = LocalDate.now();
    LocalDate withYear = localDate.withYear(2025);
    System.out.println(withYear); // 2025-05-31
}

判断时间先后

  • isAfter(ChronoLocalDateTime<?> other):检查此日期时间是否在指定的日期时间之后;
  • isBefore(ChronoLocalDateTime<?> other):检查此日期时间是否在指定的日期时间之前;

ZonedDateTime

LocalDateTime 表示本地日期和时间,要表示一个带时区的日期和时间,我们就需要 ZonedDateTime。可以简单地把 ZonedDateTime 理解成 LocalDateTime 加 ZoneId。ZoneId 是java.time 引入的新的时区类,注意和旧的java.util.TimeZone 区别。

// 默认时区
ZonedDateTime date = ZonedDateTime.now(); 
// 指定时区
ZonedDateTime date = ZonedDateTime.now(ZoneId.of("America/New_York")); 
// 解析时间
ZonedDateTime date = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
// 通过 LocalDateTime 指定 ZoneID
LocalDateTime ldt = LocalDateTime.of(2019, 9, 15, 15, 16, 17);
ZonedDateTime date = ldt.atZone(ZoneId.systemDefault());
ZonedDateTime date = ldt.atZone(ZoneId.of("America/New_York"));

Duration和Period

  • Duration 表示两个时刻之间的时间间隔。
  • Period 表示两个日期之间的天数:

    Instant 时间戳

    Instant.now() 获取当前时间戳,效果和 System.currentTimeMillis() 类似
    Instant now = Instant.now();
    // 转 ZonedDateTime
    ZonedDateTime zdt = now.atZone(ZoneId.systemDefault());
    

    DateTimeFormatter

    LocalDateTime dateTime = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    dateTime.format(formatter);
    
    https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
    查看文档中的常量实例和格式化规则~

    新旧API之间的转换

    Date -> LocalDateTime

    ```java /**
    • Date -> LocalDate
    • Date -> Instant -> ZonedDateTime -> LocalDate/LocalDateTime *
    • @param date date
    • @return LocalDate/LocalDateTime */ public static LocalDate toLocalDate(Date date) { return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); }

public static LocalDateTime toLocalDateTime(Date date) { return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); }

<a name="pH0ic"></a>
## LocalDateTime -> Date
```java
/**
 * LocalDateTime -> Date
 * LocalDate/LocalDateTime -> ZonedDateTime -> Instant -> Date
 *
 * @param localDate LocalDate/localDateTime
 * @return Date
 */
public static Date toDate(LocalDate localDate) {
    return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
}

public static Date toDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}