首页 > 编程语言 >Java-时间日期类

Java-时间日期类

时间:2024-08-29 22:56:59浏览次数:7  
标签:Java System 日期 时间 time println now out

        在Java中,处理日期和时间的类主要集中在 java.time 包中,这是自Java 8引入的新的日期和时间API。以下是一些常用的类及其方法.

1. LocalDate

LocalDate 表示不带时区的日期。

常用方法示例:

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

public class LocalDateExample {
    public static void main(String[] args) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        System.out.println("Today's date: " + today);

        // 创建特定日期
        LocalDate specificDate = LocalDate.of(2023, 10, 1);
        System.out.println("Specific date: " + specificDate);

        // 格式化日期
        String formattedDate = today.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
        System.out.println("Formatted date: " + formattedDate);

        // 获取年、月、日
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day);

        // 添加天数
        LocalDate futureDate = today.plusDays(10);
        System.out.println("Date after 10 days: " + futureDate);

        // 减少天数
        LocalDate pastDate = today.minusDays(10);
        System.out.println("Date before 10 days: " + pastDate);
    }
}

2. LocalTime

LocalTime 表示不带时区的时间。

常用方法示例:

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

public class LocalTimeExample {
    public static void main(String[] args) {
        // 获取当前时间
        LocalTime now = LocalTime.now();
        System.out.println("Current time: " + now);

        // 创建特定时间
        LocalTime specificTime = LocalTime.of(14, 30, 0);
        System.out.println("Specific time: " + specificTime);

        // 格式化时间
        String formattedTime = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        System.out.println("Formatted time: " + formattedTime);

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

        // 添加小时
        LocalTime futureTime = now.plusHours(2);
        System.out.println("Time after 2 hours: " + futureTime);

        // 减少分钟
        LocalTime pastTime = now.minusMinutes(30);
        System.out.println("Time before 30 minutes: " + pastTime);
    }
}

3. LocalDateTime

LocalDateTime 表示不带时区的日期和时间。

常用方法示例:

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

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

        // 创建特定日期和时间
        LocalDateTime specificDateTime = LocalDateTime.of(2023, 10, 1, 14, 30, 0);
        System.out.println("Specific date and time: " + specificDateTime);

        // 格式化日期和时间
        String formattedDateTime = now.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
        System.out.println("Formatted date and time: " + formattedDateTime);

        // 获取年、月、日、小时、分钟、秒
        int year = now.getYear();
        int month = now.getMonthValue();
        int day = now.getDayOfMonth();
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();
        System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day +
                           ", Hour: " + hour + ", Minute: " + minute + ", Second: " + second);

        // 添加天数和小时
        LocalDateTime futureDateTime = now.plusDays(1).plusHours(2);
        System.out.println("Date and time after 1 day and 2 hours: " + futureDateTime);

        // 减少分钟和秒
        LocalDateTime pastDateTime = now.minusMinutes(30).minusSeconds(15);
        System.out.println("Date and time before 30 minutes and 15 seconds: " + pastDateTime);
    }
}

4. ZonedDateTime

ZonedDateTime 表示带时区的日期和时间。

常用方法示例:

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

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        // 获取当前带时区的日期和时间
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println("Current date and time with zone: " + now);

        // 创建特定带时区的日期和时间
        ZonedDateTime specificZonedDateTime = ZonedDateTime.of(2023, 10, 1, 14, 30, 0, 0, ZoneId.of("America/New_York"));
        System.out.println("Specific date and time with zone: " + specificZonedDateTime);

        // 格式化带时区的日期和时间
        String formattedZonedDateTime = now.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss z"));
        System.out.println("Formatted date and time with zone: " + formattedZonedDateTime);

        // 获取时区
        ZoneId zone = now.getZone();
        System.out.println("Time zone: " + zone);

        // 转换时区
        ZonedDateTime convertedDateTime = now.withZoneSameInstant(ZoneId.of("Europe/London"));
        System.out.println("Converted date and time to Europe/London: " + convertedDateTime);
    }
}

5. DateTimeFormatter

DateTimeFormatter 用于格式化和解析日期时间对象。

常用方法示例:

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

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

        // 使用预定义格式
        String formattedDateTime1 = now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        System.out.println("ISO Local Date Time: " + formattedDateTime1);

        // 使用本地化格式
        String formattedDateTime2 = now.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM));
        System.out.println("Localized Medium Date Time: " + formattedDateTime2);

        // 使用自定义模式
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss");
        String formattedDateTime3 = now.format(customFormatter);
        System.out.println("Custom Date Time: " + formattedDateTime3);

        // 解析字符串为日期时间对象
        String dateTimeString = "01 Oct 2023 14:30:00";
        LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, customFormatter);
        System.out.println("Parsed Date Time: " + parsedDateTime);
    }
}

6.Date 

  Date 类表示特定的瞬间,精确到毫秒。尽管它仍然在使用,但推荐在新的代码中用 java.time 包中的类。

import java.util.Date;
import java.text.SimpleDateFormat;

public class DateExample {
    public static void main(String[] args) {
        // 获取当前日期和时间
        Date now = new Date();
        System.out.println("Current date and time: " + now);

        // 格式化日期和时间
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        String formattedDate = formatter.format(now);
        System.out.println("Formatted date and time: " + formattedDate);

        // 创建特定日期和时间
        Date specificDate = new Date(1234567890000L); // 2009-02-13 23:31:30 UTC
        System.out.println("Specific date and time: " + specificDate);
    }
}

 带时区和不带时区的区别

带时区和不带时区的日期时间类在表示和处理日期时间时有显著的区别:

  1. 不带时区的日期时间类

    • LocalDate:只包含日期,不包含时间和时区信息。
    • LocalTime:只包含时间,不包含日期和时区信息。
    • LocalDateTime:包含日期和时间,但不包含时区信息。

    这些类适用于不需要考虑时区的场景,例如本地事件、生日、会议时间等。

  2. 带时区的日期时间类

    • ZonedDateTime:包含日期、时间和时区信息。

    ZonedDateTime 适用于需要考虑时区的场景,例如国际航班时间、全球事件时间等。它能够准确地表示一个特定时区的日期和时间,并且在时区之间进行转换时能够正确处理夏令时和时区偏移。

        在Java中,java.time 包提供了多个类来处理日期和时间,每个类都有其特定的用途和使用场景。以下是这些类的区别以及使用场景的详细说明:

使用场景和用法区别 :

1. LocalDate

  • 区别LocalDate 表示不带时区的日期,只包含年、月、日。
  • 使用场景:适用于只需要表示日期的场景,例如生日、节假日等。

2. LocalTime

  • 区别LocalTime 表示不带时区的时间,只包含小时、分钟、秒和纳秒。
  • 使用场景:适用于只需要表示时间的场景,例如会议时间、闹钟时间等。

3. LocalDateTime

  • 区别LocalDateTime 表示不带时区的日期和时间,包含年、月、日、小时、分钟、秒和纳秒。
  • 使用场景:适用于需要同时表示日期和时间的场景,例如航班时间、会议开始时间等。

4. ZonedDateTime

  • 区别ZonedDateTime 表示带时区的日期和时间,包含年、月、日、小时、分钟、秒、纳秒以及时区信息。
  • 使用场景:适用于需要考虑时区的场景,例如国际航班时间、全球事件时间等。

5. DateTimeFormatter

  • 区别DateTimeFormatter 用于格式化和解析日期时间对象,支持多种预定义格式和自定义格式。
  • 使用场景:适用于需要将日期时间对象转换为字符串或从字符串解析为日期时间对象的场景,例如日志记录、数据存储和展示等。

 示例:

以下是一个综合示例,展示了如何在不同场景中使用这些类:

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class DateTimeExample {
    public static void main(String[] args) {
        // 示例1: 使用 LocalDate
        LocalDate birthday = LocalDate.of(1990, 5, 15);
        System.out.println("Birthday: " + birthday);

        // 示例2: 使用 LocalTime
        LocalTime meetingTime = LocalTime.of(14, 30);
        System.out.println("Meeting Time: " + meetingTime);

        // 示例3: 使用 LocalDateTime
        LocalDateTime flightTime = LocalDateTime.of(2023, 10, 1, 10, 30);
        System.out.println("Flight Time: " + flightTime);

        // 示例4: 使用 ZonedDateTime
        ZonedDateTime globalEventTime = ZonedDateTime.of(2023, 10, 1, 14, 30, 0, 0, ZoneId.of("America/New_York"));
        System.out.println("Global Event Time: " + globalEventTime);

        // 示例5: 使用 DateTimeFormatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        String formattedFlightTime = flightTime.format(formatter);
        System.out.println("Formatted Flight Time: " + formattedFlightTime);

        // 解析字符串为 LocalDateTime
        String dateTimeString = "01/10/2023 10:30:00";
        LocalDateTime parsedFlightTime = LocalDateTime.parse(dateTimeString, formatter);
        System.out.println("Parsed Flight Time: " + parsedFlightTime);
    }
}

总结

  • Date 类:早期用于处理日期和时间的类,存在一些设计上的缺陷,推荐使用 java.time 包中的类。
  • 不带时区的日期时间类:适用于不需要考虑时区的场景。
  • 带时区的日期时间类:适用于需要考虑时区的场景,能够准确表示特定时区的日期和时间,并处理时区转换。

通过合理选择这些类,可以更方便地处理不同场景下的日期和时间需求。

标签:Java,System,日期,时间,time,println,now,out
From: https://blog.csdn.net/Broken_x/article/details/141690166

相关文章

  • Java LeetCode 练习
        3142.判断矩阵是否满足条件需求:        给你一个大小为mxn的二维矩阵grid。你需要判断每一个格子grid[i][j]是否满足:        如果它下面的格子存在,那么它需要等于它下面的格子,也就是grid[i][j]==grid[i+1][j]。        ......
  • 从匿名内部类到Lambda表达式:Java编程的优雅进化
    匿名内部类首先我们先来介绍一下什么是匿名内部类匿名内部类:java中一种特殊的类定义方式,它允许你在需要实现一个接口或继承一个类的地方直接定义一个该接口或类的匿名子类。若想创建一个派生类的对象,并且对象只创建一次,可以设计为匿名内部类,可以大大简化代码注意:匿名内部类......
  • Java核心API——io类缓冲流
    在前面的学习中我们学习了如何向文件中简单的传输写入数据java将流分为两类节点流与处理流节点流:又称为低级流,特点:实际连接程序与另一端的"管道",负责实际读写数据的流.IO一定是建立在某个低级流的基础上进行的.文件流就是低级流,它们是实际连接程序与文件的管道,负责......
  • Java中的String、StringBuilder、StringBuffer
            在Java中,String、StringBuilder 和 StringBuffer 是处理字符串的三个常用类,它们各有特点和适用场景。以下是对这三个类的详细解释、常用方法的代码示例以及它们之间的区别和适用场景。StringString 类表示不可变的字符序列。一旦创建,String 对象的内容......
  • Java Script网页设计案例
    1.JavaScript网页设计案例下面我将提供一个简单的JavaScript网页设计案例,该案例将实现一个动态的待办事项列表(TodoList)。用户可以在页面上添加新的待办事项,标记它们为已完成,以及删除它们。这个案例将使用HTML来构建页面结构,CSS来美化页面,以及JavaScript来添加动态功能。1.1HT......
  • 一篇文章讲清楚Java中的反射
    介绍每个类都有一个Class对象,包含了与类有关的信息。当编译一个新类时,会产生一个同名的.class文件,该文件内容保存着Class对象。类加载相当于Class对象的加载。类在第一次使用时才动态加载到JVM中,可以使用Class.forName("com.mysql.jdbc.Driver")这种方式来控制类的加......
  • JavaScript开发学习札记:一位Java后端程序员的成长之路
    前言:        这是一篇关于JavaScript的学习笔记,目的是针对java后端开发人员,快速入门并掌握JavaScript这门语言的基本使用,并且能够进入下一阶段框架的学习。引言:为什么学习JavaScript?JavaScript是web开发人员必须学习的3门语言中的一门:HTML定义了网页的内......
  • java.time包时间类浅谈
    Java早期日期时间API:java.util.Date与java.util.Calendar一、背景在Java的早期版本中,处理日期和时间的需求主要由java.util.Date类和随后加入的java.util.Calendar类来满足。这两个类在Java1.0和Java1.1中分别被引入,为Java程序提供了基本的日期和时间操作能力。然而,随着......
  • 一篇文章讲清楚Java中的反射
    介绍每个类都有一个Class对象,包含了与类有关的信息。当编译一个新类时,会产生一个同名的.class文件,该文件内容保存着Class对象。类加载相当于Class对象的加载。类在第一次使用时才动态加载到JVM中,可以使用Class.forName("com.mysql.jdbc.Driver")这种方式来控制类的......
  • 2024年高频Java面试题
    1、java反射的作用与原理1、定义:反射机制是在运行时,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意个对象,都能够调用它的任意一个方法。在java中,只要给定类的名字,就可以通过反射机制来获得类的所有信息。这种动态获取的信息以及动态调用对象的方法的功能称为Ja......