Java 中的日期与时间处理!

简介: Java 中的日期与时间处理!

前言

学习 Java 的过程中,难免会跟时间处理打交道,那我们今天就来看看,Java 中最常见的一些日期和时间处理的知识。


基本概念

本地时间

即所处地区所处时区的时间;


时区

要准确表达时间,还要依赖时区,时区表达方式主要有如下三种:


GMT 或 UTC 加时区偏移表示 ,如 GMT+08:00 表示东八区;

缩写 ,如 CST 表示中国标准世界,但同时也表示美国中部时间;

洲 / 城市,如 Asia/Shanghai;

本地化

使用 Locale 表示一个国家或地区的日期、时间、数字、货币等格式,由 语言_国家 的字母缩写构成;


Date 和 Calendar

时间戳

Epoch Time ,即时间戳,在不同编程语言中有如下几种存储方式:


以秒为单位的整数,缺点是只能精确到秒;

以毫秒为单位的整数,最后 3 位表示毫秒数;

以秒为单位的浮点数,小数点后表示零点几秒;

标准库 API

主要提供了两套处理时间和日期的 API:


定义在 java.util 中,主要包括 Date、Calendar、TimeZone 这几个类;

定义在 java.time 中,主要包括 LocalDateTime、ZoneDateTime、ZoneId 等,自 Java 8 引入;

Date

基本用法


import java.util.*;
public class Main{
    public static void main(String[] args) throws Exception{
        // 获取当前时间
        Date date = new Date();
        // 年份
        System.out.println(date.getYear() + 1900);
        // 月份
        System.out.println(date.getMonth() + 1);
        // 日期
        System.out.println(date.getDate);
    // 转换为本地时间
        System.out.println(date.toLocaleString());
        // 转换为 GMT 时区
        System.out.println(date.toGMTString());
    }
}
  • 预定义的字符串
  • yyyy:年
  • MM:月
  • dd:日
  • HH:小时
  • mm:分钟
  • ss:秒
  • 存在的问题
  • 不能转换时区;
  • 无法对日期和时间进行运算操作;

Calendar

可用于获取并设置年、月、日、时、分、秒,比 Date 多了一个可以作简单日期和时间运算的功能;

  • 基本用法
import java.util.*;
public class Main{
    public staitc void main(String[] args) throws Exception{
        // 获取当前时间
        Calendar cal = Calendar.getInstance();
        // 获取年、月、日、时、分、秒
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
    }
}

利用 getTime() 方法,可以将一个 Calendar 对象转换为 Date 对象,然后利用 SimpleDateFormat 进行格式化;

TimeZone

相较于 Date 和 Calendar ,提供了时区转换功能,主要步骤如下:


清除所有字段;

设定指定时区;

设定日期和时间;

创建 SimpleDateFormat 并设定目标时区;

格式化获取的 Date 对象(对象无时区信息,时区信息存储在 SimpleDateFormat 中);


import java.util.*;
import java.text.*;
public class Main{
    public static void main(String[] args) throws Exception{
        Calendar cal = Calendar.getInstance();
        cal.clear();
        // 设定时区
        cal.setTimeZone(TimZone.getTimeZone("Asia/Shanghai"));
        // 设定时间
        cal.set(2020, 3 /* 4 月 */, 25, 13, 30, 0);
    // 显示时间:
        var sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
        System.out.println(sdf.format(c.getTime()));
    }
}

LocalDateTime

Java 8 引入 java.time 中所提供的新的时间和日期 API,主要涉及的类型:


本地日期和时间:LocalDateTime、LocalDate、LocalTime

带时区的日期和时间:ZonedDateTime

时刻:Instant

时区:ZoneId、ZoneOffset

时间间隔:Duration

格式化:DateTimeFormatter

基本用法


import java.time.*;
public class Main{
    public static void main(String[] args) throws Exception{
        // 当前日期
        LocalDate date = LocalDate.now();
        // 当前时间
        LocalTime time = LocalTime.now();
        // 当前日期和时间
        LocalDateTime dateTime = LocalDateTime.now();
    }
}

输出标准为 ISO 8601,日期和时间之间的分割符是 T ,规定的标准格式如下:

日期:yyyy-MM-dd

时间:HH:mm:ss

带毫秒的时间:HH:mm:ss.SSS

日期和时间:yyyy-MM-dd T HH:mm:ss

带毫秒的日期和时间:yyyy-MM-dd T HH:mm:ss.SSS

对日期和时间进行调整:

年:withYear()

月:withMonth()

日:withDayOfMonth()

时:withHour()

分:withMinute()

秒:withSecond()

Duration 和 Period

Duration:表示两个时刻间的时间间隔;

Period:表示两个日期之间的天数;

ZonedDateTime

用于表示带时区的日期和时间;


时区转换及本地时间转换


import java.time.*;
public class Main{
    public static void main(String[] args) throws Exception{
        ZonedDateTime zoneTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        // 中国时区转换为纽约时间
        ZonedDateTime newZoneTime = zoneTime.withZoneSameInstant(ZoneId.of("America/New_York"));
        // 转换为本地时间
        LocalDateTime local = zoneTime.toLocalDateTime();
        System.out.println(zoneTime);
        System.out.println(newZoneTime);
    }
}

DateTimeFormatter

相较于 SimpleDateFormat ,DateTimeFormatter 不仅是不变对象,还是线程安全的,有如下两种使用方式;


传入格式化字符串

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

1

传入格式化字符串同时指定 Locale

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, yyyy-MM-dd HH:mm:ss", Locale.US)

1

对比效果


import java.time.*;
import java.time.format.*;
import java.util.Locale;
public class Main{
    public static void main(String[] args) throws Exception{
        ZonedDateTime zdt = ZonedDateTime.new();
        var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm ZZZZ");
        System.out.println(formatter.format(zdt));
        var zhFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd EE HH:mm", Locale.CHINA);
        System.out.println(zhFormatter.format(zdt));
        var usFormatter = DateTimeFormatter.ofPattern("E, MMMM/dd/yyyy EE HH:mm", Locale.US);
        System.out.println(usFormatter.format(zdt));
    }
}

Instance

时间戳在 java.time 中用 Instant 类型表示,相当于 java.util 中的 currentTimeMills() ,返回以毫秒表示的当前时间戳;


Instant 内部核心字段

public final class Instant implements ...{

   private final long seconds;

   private final int nanos;

}


LocalDateTie、ZoneId、Instant、ZonedDateTime、long 之间相互转换关系;


image.png

总结

以上就是 Java 中关于日期和时间的相关学习笔记了,如果你觉得我整理的笔记对你也有用,那就点个赞再走吧!

目录
相关文章
|
1月前
|
Java
Java基础之日期和时间
Java基础之日期和时间
20 1
|
2月前
|
安全 Java 程序员
Java8实战-新的日期和时间API
Java8实战-新的日期和时间API
31 3
|
6天前
|
前端开发 JavaScript Java
【前端学java】java中的日期操作(13)
【8月更文挑战第10天】java中的日期操作
9 2
【前端学java】java中的日期操作(13)
|
3月前
|
安全 Java Unix
Java语言中的日期与时间处理技术
Java语言中的日期与时间处理技术
|
1月前
|
Java API
Java基础之日期和时间
【7月更文挑战第4天】 Java日期时间API概览:Java 8之前,Date表示不可变时间点,Calendar用于计算,SimpleDateFormat处理格式化。Date的setXXX方法不推荐,Calendar支持加减操作。时区处理用TimeZone,Time仅处理时间(不含日期)。Java 8引入java.time包,提供Instant、LocalDate等线程安全类,改进了性能和易用性,支持时区和更复杂操作。后续将探讨Java 8的新特性!
21 1
|
1月前
|
安全 Java API
Java基础之日期和时间
【7月更文挑战第3天】 Java 8之前的日期时间处理涉及Date、Calendar、SimpleDateFormat及TimeZone类。Date是不可变对象,但不推荐直接调整时间。Calendar提供日期计算,而SimpleDateFormat用于格式化。Date和Calendar非线程安全,处理时区需用TimeZone。Java 8引入了java.time包,包含Instant、LocalDate等类,提供更现代、线程安全和高效的API,例如Instant用于时间戳,LocalDateTime表示日期和时间,ZonedDateTime处理时区。下节将探讨Java 8的新API。
32 2
|
1月前
|
Java API
Java中的日期和时间API详解
Java中的日期和时间API详解
|
2月前
|
Java 测试技术 API
滚雪球学Java(52):一步一步教你使用Java Calendar类进行日期计算
【6月更文挑战第6天】🏆本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
24 3
滚雪球学Java(52):一步一步教你使用Java Calendar类进行日期计算
|
2月前
|
Java
2021蓝桥杯大赛软件类国赛Java大学B组 完全日期 复杂遍历搜索
2021蓝桥杯大赛软件类国赛Java大学B组 完全日期 复杂遍历搜索
31 2
|
1月前
|
安全 Java API
Java基础之新日期和时间
“【7月更文挑战第6天】”Java 8 引入了`java.time`包,改进了日期和时间处理。新API包括:`LocalDate`(线程安全的日期)、`LocalTime`(时间)、`LocalDateTime`(日期和时间)、`ZonedDateTime`(带时区的日期和时间)、`Instant`(时间戳)、`DateTimeFormatter`(线程安全的格式化器)、`Period`(日期间隔)和`Duration`(时间间隔)。
20 0