详细分析Java中的LocalDateTime类

本文介绍了Java8中LocalDateTime类的基本知识,包括其概念、作用、特点,展示了常用方法如获取当前时间、创建指定日期、日期时间操作、格式化和解析等,并给出了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

一开始使用Date类来表述时间属性
一个问题是 时间戳的问题,另一个问题是读取Excel数据格式的时候没有那么灵活

1. 基本知识

LocalDateTime是Java 8引入的日期和时间API中的一个类,位于java.time包中。

它提供了一种更灵活、更方便的方式来处理日期和时间,相比旧的Date类更为强大且易用。

以下是关于LocalDateTime的详细分析:

  • 概念LocalDateTime表示不带时区的日期和时间。
    包含了年、月、日、时、分、秒等信息,可以精确到纳秒级别。
    Date类不同,LocalDateTime不受时区的影响,更适合处理应用程序中不涉及时区转换的日期和时间。

  • 作用: LocalDateTime用于表示和处理不带时区信息的日期和时间,适用于大多数应用场景,特别是与用户直接交互或与本地系统相关的情况。


LocalDateTime类的关键特征:

  1. LocalDateTime是java.time包中的一个不可变类(immutable class)。
  2. 内部实现使用了LocalDate和LocalTime。
  3. 不包含时区信息,是一个本地日期和时间的组合。

最主要的特性如下:

  1. 不可变性(Immutability): LocalDateTime是不可变的,这意味着一旦创建了对象,就无法更改其内容。任何对日期和时间的修改都会返回一个新的LocalDateTime对象。

  2. 线程安全性: 由于不可变性,LocalDateTime是线程安全的。多个线程可以同时访问对象而无需担心并发问题。

  3. 工厂方法: 除了使用of方法创建LocalDateTime对象外,还有一些静态工厂方法,如now、ofInstant、ofEpochSecond等,用于根据不同的情况创建实例。

  4. 日期时间调整: LocalDateTime提供了plus、minus等方法,用于执行日期和时间的调整操作。这些方法返回新的对象,而不是修改原始对象。

  5. 格式化和解析: LocalDateTime支持DateTimeFormatter用于格式化和解析日期时间。你可以创建自定义的格式化模式。

2. 常用方法

API表达意义
LocalDateTime.now()获取当前日期和时间
LocalDateTime.of(year, month, day, hour, minute)指定年、月、日、时、分生成一个新的 LocalDateTime 对象
LocalDateTime.plusDays(days)在当前日期时间上加指定的天数
LocalDateTime.plusHours(hours)在当前时间上加指定的小时数
LocalDateTime.minusDays(days)在当前日期时间上减去指定的天数
LocalDateTime.minusHours(hours)在当前时间上减去指定的小时数
LocalDateTime.getYear()获取年份
LocalDateTime.getMonth()获取月份,返回 Month 枚举值
LocalDateTime.getDayOfMonth()获取月中的某一天
LocalDateTime.getDayOfWeek()获取星期几,返回 DayOfWeek 枚举值
LocalDateTime.getHour()获取当前小时数
LocalDateTime.getMinute()获取当前分钟数
LocalDateTime.withYear(year)设置指定年份,返回一个新的 LocalDateTime 对象
LocalDateTime.withMonth(month)设置指定月份,返回一个新的 LocalDateTime 对象
LocalDateTime.withDayOfMonth(day)设置指定的月份天数,返回一个新的 LocalDateTime 对象
LocalDateTime.withHour(hour)设置指定的小时数,返回一个新的 LocalDateTime 对象
LocalDateTime.withMinute(minute)设置指定的分钟数,返回一个新的 LocalDateTime 对象
LocalDateTime.toLocalDate()返回 LocalDate 对象,仅包含日期部分
LocalDateTime.toLocalTime()返回 LocalTime 对象,仅包含时间部分
LocalDateTime.isBefore(dateTime)判断当前 LocalDateTime 是否在给定的时间之前
LocalDateTime.isAfter(dateTime)判断当前 LocalDateTime 是否在给定的时间之后

之所以了解这些API列表,是因为用到了增加32个小时的需求

在这里插入图片描述

  1. 获取当前日期时间:
LocalDateTime currentDateTime = LocalDateTime.now();
  1. 创建指定日期时间:
LocalDateTime specificDateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 30);
  1. 获取日期和时间部分:
LocalDate datePart = specificDateTime.toLocalDate();
LocalTime timePart = specificDateTime.toLocalTime();
  1. 日期时间加减操作:
LocalDateTime newDateTime = specificDateTime.plusDays(1).minusHours(3);
  1. 比较:
boolean isAfter = specificDateTime.isAfter(currentDateTime);
  1. 格式化和解析:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = specificDateTime.format(formatter);

LocalDateTime parsedDateTime = LocalDateTime.parse("2022-01-01 12:30:00", formatter);

类似的Demo如下:

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

public class LocalDateTimeExample {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("Current DateTime: " + currentDateTime);

        // 创建指定日期时间
        LocalDateTime specificDateTime = LocalDateTime.of(2022, 1, 1, 12, 30);
        System.out.println("Specific DateTime: " + specificDateTime);

        // 比较
        boolean isAfter = specificDateTime.isAfter(currentDateTime);
        System.out.println("Is specificDateTime after currentDateTime? " + isAfter);

        // 格式化和解析
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = specificDateTime.format(formatter);
        System.out.println("Formatted DateTime: " + formattedDateTime);

        LocalDateTime parsedDateTime = LocalDateTime.parse("2022-01-01 12:30:00", formatter);
        System.out.println("Parsed DateTime: " + parsedDateTime);
    }
}

截图如下:

在这里插入图片描述


对于上述的API为获取整体,如果获取细节也是可以的!

  1. 获取年份:(返回LocalDateTime对象的年份部分)
int year = localDateTime.getYear();
  1. 获取月份:(返回LocalDateTime对象的月份部分)
Month month = localDateTime.getMonth(); //getMonth()返回Month枚举类型
int monthValue = localDateTime.getMonthValue(); //getMonthValue()返回月份的整数值
  1. 获取天(日):
int dayOfMonth = localDateTime.getDayOfMonth(); //返回月份中的天数。
int dayOfYear = localDateTime.getDayOfYear(); //返回年份中的天数。
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();//返回星期几,返回的是DayOfWeek枚举类型。
  1. 获取小时、分钟、秒:(返回LocalDateTime对象的时、分、秒部分)
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();
  1. 其他时间信息:(返回纳秒部分)
int nano = localDateTime.getNano();

示例的Demo如下:

import java.time.*;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.now();

        // 获取年份
        int year = localDateTime.getYear();
        System.out.println("Year: " + year);

        // 获取月份
        Month month = localDateTime.getMonth();
        int monthValue = localDateTime.getMonthValue();
        System.out.println("Month: " + month + " (" + monthValue + ")");

        // 获取天(日)
        int dayOfMonth = localDateTime.getDayOfMonth();
        int dayOfYear = localDateTime.getDayOfYear();
        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
        System.out.println("Day of Month: " + dayOfMonth);
        System.out.println("Day of Year: " + dayOfYear);
        System.out.println("Day of Week: " + dayOfWeek);

        // 获取小时、分钟、秒
        int hour = localDateTime.getHour();
        int minute = localDateTime.getMinute();
        int second = localDateTime.getSecond();
        System.out.println("Hour: " + hour);
        System.out.println("Minute: " + minute);
        System.out.println("Second: " + second);

        // 获取其他时间信息
        int nano = localDateTime.getNano();
        System.out.println("Nano: " + nano);
    }
}

截图如下:

在这里插入图片描述

3. 当前时间戳

import java.text.SimpleDateFormat;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        // 获取当前 LocalDateTime 对象
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 将 LocalDateTime 转换为 Instant
        Instant instant = currentDateTime.toInstant(ZoneOffset.of("+8"));

        // 获取时间戳
        long timestamp = instant.toEpochMilli();
        System.out.println("Current Timestamp with LocalDateTime: " + timestamp);

        //时间戳格式转换
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(df.format(timestamp));
    }
}

或者另外一种表达方式:

// 获取当前 LocalDateTime 对象
LocalDateTime currentDateTime = LocalDateTime.now(Clock.systemUTC());

// 将 LocalDateTime 转换为 Instant
Instant instant = currentDateTime.toInstant(ZoneOffset.UTC);

最终截图如下:

在这里插入图片描述

4. 格式转换

常用的格式转换为String与LocalDateTime之间!

常用的方法有个格式转换的概括,但此处重点拿出来讲一讲:

一、String 转换为 LocalDateTime:

public class LocalDateTimeExample {
    public static void main(String[] args) {
        // String 转换为 LocalDateTime
        String dateStr = "2024-01-21 21:00:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parsedDate = LocalDateTime.parse(dateStr, formatter);
        System.out.println(parsedDate);

        // String 转换为 LocalDate
        String dateStr2 = "2024-01-21 21:00:00";
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate parsedDate2 = LocalDate.parse(dateStr2, formatter2);
        System.out.println(parsedDate2);

    }
}

截图如下:

在这里插入图片描述

二、

public class LocalDateTimeExample {
    public static void main(String[] args) {
        LocalDateTime date = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatedDateStr = date.format(formatter);
        System.out.println("-------" + formatedDateStr);

    }
}

截图如下:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值