当前位置:首页 > 技术 > 正文内容

Java 8 日期时间格式化指南

访客 技术 2026年7月6日 1

Java 8 日期时间格式化指南

Java 8 引入的新日期时间 API 提供了强大的格式化功能,使日期时间的格式化和解析变得简单直观。格式化是将日期时间对象转换为字符串的过程,而解析则是将字符串转换回日期时间对象。

1. DateTimeFormatter 类

DateTimeFormatterjava.time.format 包中的核心类,用于格式化和解析日期时间。它既可以使用预定义的格式器,也可以创建自定义格式器。

创建 DateTimeFormatter


import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class DateFormatDemo {

    public static void main(String[] args) {
        // 获取当前日期和时间
        LocalDate currentDate = LocalDate.now();
        LocalTime currentTime = LocalTime.now();

        // 使用预定义格式器
        DateTimeFormatter standardFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
        String formattedDate = standardFormatter.format(currentDate);
        System.out.println("标准格式日期: " + formattedDate);

        // 创建自定义格式器
        DateTimeFormatter patternFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String customFormattedDate = patternFormatter.format(currentDate);
        System.out.println("自定义格式日期: " + customFormattedDate);
    }
}

2. 日期时间格式化

使用 DateTimeFormatter 可以轻松将日期时间对象格式化为字符串。

格式化示例


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

public class TimeFormattingDemo {

    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();

        // 使用 ISO 格式
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        String isoResult = now.format(isoFormatter);
        System.out.println("ISO 格式: " + isoResult);

        // 使用自定义模式
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        String customResult = now.format(customFormatter);
        System.out.println("自定义格式: " + customResult);
    }
}

3. 日期时间解析

同样可以使用 DateTimeFormatter 将字符串解析为日期时间对象。

解析示例


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

public class TimeParsingDemo {

    public static void main(String[] args) {
        String dateStr = "2023-08-15T14:30:00";

        // 使用 ISO 格式解析
        DateTimeFormatter isoFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        LocalDateTime parsedDateTime = LocalDateTime.parse(dateStr, isoFormatter);
        System.out.println("解析结果: " + parsedDateTime);

        // 使用自定义格式解析
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            LocalDateTime customParsed = LocalDateTime.parse("2023-08-15 14:30:00", customFormatter);
            System.out.println("自定义解析结果: " + customParsed);
        } catch (DateTimeParseException e) {
            System.out.println("日期时间解析失败: " + e.getMessage());
        }
    }
}

4. 时区日期时间格式化

DateTimeFormatter 同样支持带时区的日期时间格式化和解析。

时区日期时间示例


import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class ZoneTimeFormattingDemo {

    public static void main(String[] args) {
        // 获取当前时区日期时间
        ZonedDateTime nowWithZone = ZonedDateTime.now();

        // 使用 ISO 格式
        DateTimeFormatter isoZoneFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
        String isoZoneResult = nowWithZone.format(isoZoneFormatter);
        System.out.println("ISO 时区格式: " + isoZoneResult);

        // 使用自定义格式
        DateTimeFormatter customZoneFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z");
        try {
            ZonedDateTime customZoneTime = ZonedDateTime.parse("2023-08-15 14:30 Asia/Shanghai", customZoneFormatter);
            System.out.println("自定义时区解析结果: " + customZoneTime);
        } catch (DateTimeParseException e) {
            System.out.println("时区日期时间解析失败: " + e.getMessage());
        }
    }
}

注意事项

  • DateTimeFormatter 是不可变类,线程安全,可在多线程环境中共享使用
  • 格式模式必须与日期时间字符串匹配,否则会抛出 DateTimeParseException
  • 格式化和解析带时区的日期时间时,格式模式中应包含时区信息
  • 预定义格式器提供了常用的标准格式,适用于大多数场景

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。