Java-时间日期类

        在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: 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值