Java日期时间案例如何实操

wen java案例 23

本文目录导读:

Java日期时间案例如何实操

  1. 基础日期时间操作
  2. 日期格式化与解析
  3. 日期计算与操作
  4. 时间戳与日期转换
  5. 实用工具类
  6. 实际业务场景案例

我来为您提供Java日期时间处理的实操案例,涵盖常用场景。

基础日期时间操作

获取当前日期时间

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
public class DateTimeBasicDemo {
    public static void main(String[] args) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        System.out.println("当前日期: " + today);  // 2024-01-15
        // 获取当前时间
        LocalTime now = LocalTime.now();
        System.out.println("当前时间: " + now);    // 14:30:25.123
        // 获取当前日期时间
        LocalDateTime dateTimeNow = LocalDateTime.now();
        System.out.println("当前日期时间: " + dateTimeNow);
    }
}

日期格式化与解析

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatDemo {
    public static void main(String[] args) {
        // 定义日期时间字符串
        String dateStr = "2024-01-15 14:30:00";
        // 创建格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析字符串为LocalDateTime
        LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);
        System.out.println("解析后的时间: " + dateTime);
        // 格式化LocalDateTime为字符串
        String formattedDate = dateTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"));
        System.out.println("格式化结果: " + formattedDate);
        // 其他常用格式
        DateTimeFormatter[] formatters = {
            DateTimeFormatter.ISO_DATE,
            DateTimeFormatter.ISO_DATE_TIME,
            DateTimeFormatter.ofPattern("yyyy/MM/dd"),
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
        };
        for (DateTimeFormatter fmt : formatters) {
            System.out.println(dateTime.format(fmt));
        }
    }
}

日期计算与操作

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class DateTimeCalculationDemo {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        // 加减天、月、年
        LocalDate nextWeek = today.plusDays(7);
        LocalDate nextMonth = today.plusMonths(1);
        LocalDate lastYear = today.minusYears(1);
        System.out.println(" " + today);
        System.out.println("一周后: " + nextWeek);
        System.out.println("一个月后: " + nextMonth);
        System.out.println("一年前: " + lastYear);
        // 计算两个日期之间的差值
        LocalDate start = LocalDate.of(2024, 1, 1);
        LocalDate end = LocalDate.of(2024, 12, 31);
        long daysBetween = ChronoUnit.DAYS.between(start, end);
        long monthsBetween = ChronoUnit.MONTHS.between(start, end);
        System.out.println("相差天数: " + daysBetween);
        System.out.println("相差月数: " + monthsBetween);
        // 使用Period计算
        Period period = Period.between(start, end);
        System.out.println("相差: " + period.getYears() + "年" + 
                          period.getMonths() + "月" + 
                          period.getDays() + "天");
    }
}

时间戳与日期转换

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class TimestampDemo {
    public static void main(String[] args) {
        // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
        System.out.println("当前时间戳(毫秒): " + currentTimestamp);
        // 获取秒级时间戳
        long secondsTimestamp = Instant.now().getEpochSecond();
        System.out.println("当前时间戳(秒): " + secondsTimestamp);
        // 时间戳转LocalDateTime
        LocalDateTime dateTime = LocalDateTime.ofInstant(
            Instant.ofEpochMilli(currentTimestamp), 
            ZoneId.systemDefault()
        );
        System.out.println("时间戳转日期: " + dateTime);
        // LocalDateTime转时间戳
        LocalDateTime now = LocalDateTime.now();
        long timestamp = now.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        System.out.println("日期转时间戳: " + timestamp);
    }
}

实用工具类

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
public class DateUtils {
    // 日期格式化
    public static String formatDate(LocalDate date, String pattern) {
        return date.format(DateTimeFormatter.ofPattern(pattern));
    }
    // 字符串转日期
    public static LocalDate parseDate(String dateStr, String pattern) {
        return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
    }
    // 获取某月的第一天
    public static LocalDate getFirstDayOfMonth(LocalDate date) {
        return date.with(TemporalAdjusters.firstDayOfMonth());
    }
    // 获取某月的最后一天
    public static LocalDate getLastDayOfMonth(LocalDate date) {
        return date.with(TemporalAdjusters.lastDayOfMonth());
    }
    // 判断是否为闰年
    public static boolean isLeapYear(int year) {
        return Year.isLeap(year);
    }
    // 计算年龄
    public static int calculateAge(LocalDate birthDate) {
        return Period.between(birthDate, LocalDate.now()).getYears();
    }
    // 获取两个日期之间的所有日期
    public static List<LocalDate> getDatesBetween(LocalDate start, LocalDate end) {
        List<LocalDate> dates = new ArrayList<>();
        LocalDate current = start;
        while (!current.isAfter(end)) {
            dates.add(current);
            current = current.plusDays(1);
        }
        return dates;
    }
    public static void main(String[] args) {
        // 使用示例
        LocalDate today = LocalDate.now();
        System.out.println(" " + formatDate(today, "yyyy-MM-dd"));
        System.out.println("当月第一天: " + getFirstDayOfMonth(today));
        System.out.println("当月最后一天: " + getLastDayOfMonth(today));
        System.out.println("2024年是否是闰年: " + isLeapYear(2024));
        System.out.println("年龄: " + calculateAge(LocalDate.of(1990, 1, 1)) + "岁");
        // 获取日期范围
        List<LocalDate> dateRange = getDatesBetween(
            LocalDate.of(2024, 1, 1),
            LocalDate.of(2024, 1, 7)
        );
        System.out.println("日期范围: " + dateRange);
    }
}

实际业务场景案例

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class BusinessDemo {
    // 场景1:计算订单超时时间
    public static boolean isOrderExpired(LocalDateTime orderTime, int expireHours) {
        LocalDateTime expireTime = orderTime.plusHours(expireHours);
        return LocalDateTime.now().isAfter(expireTime);
    }
    // 场景2:判断是否在营业时间内
    public static boolean isInBusinessHours(LocalTime now) {
        LocalTime openTime = LocalTime.of(9, 0);
        LocalTime closeTime = LocalTime.of(18, 0);
        return !now.isBefore(openTime) && !now.isAfter(closeTime);
    }
    // 场景3:计算工作日天数(排除周末)
    public static long countWorkDays(LocalDate start, LocalDate end) {
        long workDays = 0;
        LocalDate current = start;
        while (!current.isAfter(end)) {
            if (current.getDayOfWeek() != DayOfWeek.SATURDAY && 
                current.getDayOfWeek() != DayOfWeek.SUNDAY) {
                workDays++;
            }
            current = current.plusDays(1);
        }
        return workDays;
    }
    // 场景4:生日提醒
    public static boolean isBirthdaySoon(LocalDate birthDate, int daysBefore) {
        LocalDate today = LocalDate.now();
        LocalDate thisYearBirthday = birthDate.withYear(today.getYear());
        // 如果今年的生日已过,计算明年
        if (thisYearBirthday.isBefore(today)) {
            thisYearBirthday = thisYearBirthday.plusYears(1);
        }
        long daysToBirthday = ChronoUnit.DAYS.between(today, thisYearBirthday);
        return daysToBirthday >= 0 && daysToBirthday <= daysBefore;
    }
    public static void main(String[] args) {
        // 使用示例
        LocalDateTime orderTime = LocalDateTime.now().minusHours(23);
        System.out.println("订单是否超时(24小时): " + isOrderExpired(orderTime, 24));
        System.out.println("是否在营业时间: " + isInBusinessHours(LocalTime.now()));
        LocalDate start = LocalDate.of(2024, 1, 1);
        LocalDate end = LocalDate.of(2024, 1, 31);
        System.out.println("工作日天数(1月): " + countWorkDays(start, end) + "天");
        LocalDate birthday = LocalDate.of(1990, 1, 20);
        System.out.println("生日是否在一周内: " + isBirthdaySoon(birthday, 7));
    }
}

这些案例涵盖了Java日期时间处理的常见场景,您可以根据实际需求进行调整和使用,建议使用Java 8+的java.time包,因为它是线程安全的,API设计更合理。

抱歉,评论功能暂时关闭!