当前位置: 首页 > news >正文

Java8 日期处理(详细版)

1. java8 - Instant

重要知识点
  • 定义Instant表示时间线上的一个瞬时点,精确到纳秒,主要用于处理机器可读的时间戳,基于 Unix 时间戳(从 1970 年 1 月 1 日 00:00:00 UTC 开始的秒数)。
  • 常用方法
    • now():获取当前的瞬时点。
    • plusSeconds(long secondsToAdd):在当前瞬时点上增加指定的秒数。
    • minusSeconds(long secondsToSubtract):在当前瞬时点上减去指定的秒数。
    • isBefore(Instant otherInstant)isAfter(Instant otherInstant):用于比较两个Instant的先后顺序。
代码示例
importjava.time.Instant;publicclassOrderService{publicvoidrecordOrderTime(){InstantorderTime=Instant.now();System.out.println("订单创建时间: "+orderTime);// 模拟订单处理 10 秒InstantprocessedTime=orderTime.plusSeconds(10);System.out.println("订单处理完成时间: "+processedTime);}}

2. java8 - LocalDate

重要知识点
  • 定义LocalDate表示一个不包含时间和时区的日期,例如 2025 - 02 - 24。
  • 创建方式
    • now():获取当前日期。
    • of(int year, int month, int dayOfMonth):根据指定的年、月、日创建日期。
代码示例
importjava.time.LocalDate;publicclassProductService{publicvoidcheckProductExpiry(){LocalDatecurrentDate=LocalDate.now();LocalDateexpiryDate=LocalDate.of(2025,12,31);if(currentDate.isAfter(expiryDate)){System.out.println("商品已过期");}else{System.out.println("商品未过期");}}}

3. java8 - LocalDate 日期加减

重要知识点
  • 方法
    • plusDays(long daysToAdd):增加指定的天数。
    • plusWeeks(long weeksToAdd):增加指定的周数。
    • plusMonths(long monthsToAdd):增加指定的月数。
    • plusYears(long yearsToAdd):增加指定的年数。
    • minusDays(long daysToSubtract)minusWeeks(long weeksToSubtract)等:用于减去相应的时间单位。
代码示例
importjava.time.LocalDate;publicclassPromotionService{publicvoidcalculatePromotionEndDate(){LocalDatestartDate=LocalDate.now();LocalDateendDate=startDate.plusDays(7);System.out.println("促销开始日期: "+startDate);System.out.println("促销结束日期: "+endDate);}}

4. java8 - LocalDate 日期加减方法续

重要知识点
  • 可以使用plus(TemporalAmount amountToAdd)minus(TemporalAmount amountToSubtract)方法进行更灵活的日期加减操作,TemporalAmount可以是Period等。
代码示例
importjava.time.LocalDate;importjava.time.Period;publicclassDeliveryService{publicvoidestimateDeliveryDate(){LocalDateorderDate=LocalDate.now();PerioddeliveryPeriod=Period.ofDays(3);LocalDateestimatedDeliveryDate=orderDate.plus(deliveryPeriod);System.out.println("订单日期: "+orderDate);System.out.println("预计送达日期: "+estimatedDeliveryDate);}}

5. java8 - LocalDate 比较日期方法

重要知识点
  • 方法
    • isBefore(LocalDate other):判断当前日期是否在指定日期之前。
    • isAfter(LocalDate other):判断当前日期是否在指定日期之后。
    • isEqual(LocalDate other):判断两个日期是否相等。
代码示例
importjava.time.LocalDate;publicclassInvoiceService{publicvoidcheckInvoiceDueDate(){LocalDatecurrentDate=LocalDate.now();LocalDatedueDate=LocalDate.of(2025,3,1);if(currentDate.isAfter(dueDate)){System.out.println("发票已逾期");}elseif(currentDate.isBefore(dueDate)){System.out.println("发票未逾期");}else{System.out.println("发票今日到期");}}}

6. java8 - LocalDate 修改年月日

重要知识点
  • 方法
    • withYear(int year):修改年份。
    • withMonth(int month):修改月份。
    • withDayOfMonth(int dayOfMonth):修改日期。
代码示例
importjava.time.LocalDate;publicclassInventoryService{publicvoidadjustInventoryUpdateDate(){LocalDateoriginalDate=LocalDate.now();LocalDateadjustedDate=originalDate.withYear(2026).withMonth(6).withDayOfMonth(15);System.out.println("原库存更新日期: "+originalDate);System.out.println("调整后的库存更新日期: "+adjustedDate);}}

7. java8 - LocalDate 使用总结

重要知识点
  • LocalDate适用于处理只涉及日期的场景,如生日、到期日期、促销日期等。它提供了丰富的日期操作方法,包括日期的创建、加减、比较和修改等,使用起来非常方便。

8. java8 - LocalTime - 1

重要知识点
  • 定义LocalTime表示一个不包含日期和时区的时间,例如 10:30:00。
  • 创建方式
    • now():获取当前时间。
    • of(int hour, int minute)of(int hour, int minute, int second)等:根据指定的时、分、秒创建时间。
代码示例
importjava.time.LocalTime;publicclassCustomerService{publicvoidcheckServiceHours(){LocalTimecurrentTime=LocalTime.now();LocalTimestartTime=LocalTime.of(9,0);LocalTimeendTime=LocalTime.of(18,0);if(currentTime.isAfter(startTime)&&currentTime.isBefore(endTime)){System.out.println("客服服务时间内");}else{System.out.println("客服休息时间");}}}

9. java8 - LocalTime - 2

重要知识点
  • 时间操作方法
    • plusHours(long hoursToAdd)plusMinutes(long minutesToAdd)等:增加相应的时间单位。
    • minusHours(long hoursToSubtract)minusMinutes(long minutesToSubtract)等:减去相应的时间单位。
    • isBefore(LocalTime other)isAfter(LocalTime other):比较时间先后。
代码示例
importjava.time.LocalTime;publicclassFlashSaleService{publicvoidcheckFlashSaleTime(){LocalTimecurrentTime=LocalTime.now();LocalTimesaleStartTime=LocalTime.of(12,0);LocalTimesaleEndTime=saleStartTime.plusHours(1);if(currentTime.isAfter(saleStartTime)&&currentTime.isBefore(saleEndTime)){System.out.println("限时抢购进行中");}else{System.out.println("限时抢购未开始或已结束");}}}

10. java8 - LocalDateTime

重要知识点
  • 定义LocalDateTime表示一个既包含日期又包含时间的对象,不包含时区信息,例如 2025 - 02 - 24T10:30:00。
  • 创建方式
    • now():获取当前的日期和时间。
    • of(LocalDate date, LocalTime time):根据LocalDateLocalTime创建LocalDateTime
    • of(int year, int month, int dayOfMonth, int hour, int minute)等:直接指定年、月、日、时、分等信息创建。
代码示例
importjava.time.LocalDate;importjava.time.LocalDateTime;importjava.time.LocalTime;publicclassOrderProcessingService{publicvoidprocessOrder(){LocalDateorderDate=LocalDate.of(2025,2,24);LocalTimeorderTime=LocalTime.of(14,30);LocalDateTimeorderDateTime=LocalDateTime.of(orderDate,orderTime);System.out.println("订单创建时间: "+orderDateTime);}}

11. java8 - LocalDateTime 总结

重要知识点
  • LocalDateTime结合了LocalDateLocalTime的功能,适用于需要同时处理日期和时间的场景,如订单创建时间、会议安排等。它继承了LocalDateLocalTime的大部分操作方法,方便进行日期和时间的组合操作。

12. java8 - MonthDay

重要知识点
  • 定义MonthDay表示一年中的某个月和日,不包含年份信息,例如 --02 - 24。
  • 用途:常用于表示每年重复的日期,如生日、纪念日等。
  • 创建方式
    • now():获取当前的月和日。
    • of(int month, int dayOfMonth):根据指定的月和日创建MonthDay
代码示例
importjava.time.MonthDay;publicclassCustomerBirthdayService{publicvoidcheckCustomerBirthday(){MonthDaycurrentMonthDay=MonthDay.now();MonthDaycustomerBirthday=MonthDay.of(2,24);if(currentMonthDay.equals(customerBirthday)){System.out.println("今天是客户的生日,发送生日祝福和优惠活动");}}}

13. java8 - YearMonth

重要知识点
  • 定义YearMonth表示一年中的某个月,包含年份和月份信息,例如 2025 - 02。
  • 用途:常用于处理与月份相关的统计、报表等业务,如每月销售额统计。
  • 创建方式
    • now():获取当前的年和月。
    • of(int year, int month):根据指定的年和月创建YearMonth
代码示例
importjava.time.YearMonth;publicclassMonthlySalesService{publicvoidcalculateMonthlySales(){YearMonthcurrentYearMonth=YearMonth.now();System.out.println("当前统计月份: "+currentYearMonth);// 模拟计算该月销售额的逻辑System.out.println("该月销售额计算完成");}}

14. java8 - Period

重要知识点
  • 定义Period用于表示两个日期之间的时间间隔,以年、月、日为单位。
  • 创建方式
    • between(LocalDate startDate, LocalDate endDate):计算两个LocalDate之间的时间间隔。
  • 常用方法
    • getYears()getMonths()getDays():分别获取时间间隔中的年、月、日数。
代码示例
importjava.time.LocalDate;importjava.time.Period;publicclassOrderDurationService{publicvoidcalculateOrderDuration(){LocalDateorderDate=LocalDate.of(2025,1,1);LocalDatedeliveryDate=LocalDate.of(2025,1,10);Periodduration=Period.between(orderDate,deliveryDate);System.out.println("订单从下单到送达历时: "+duration.getDays()+" 天");}}

15. java8 - Period 使用总结

重要知识点
  • Period主要用于处理日期之间的间隔,以年、月、日为单位进行计算。在处理与日期跨度相关的业务场景时非常有用,如计算订单处理周期、会员有效期等。

16. java8 - Duration

重要知识点
  • 定义Duration用于表示两个时间点之间的时间间隔,以秒和纳秒为单位,适用于处理更精确的时间间隔,如程序执行时间、视频播放时长等。
  • 创建方式
    • between(Temporal startInclusive, Temporal endExclusive):计算两个Temporal对象(如LocalDateTimeInstant等)之间的时间间隔。
  • 常用方法
    • getSeconds():获取时间间隔的秒数。
    • toMinutes()toHours()toDays():将时间间隔转换为分钟、小时、天。
代码示例
importjava.time.Duration;importjava.time.LocalDateTime;publicclassPaymentProcessingService{publicvoidmeasurePaymentProcessingTime(){LocalDateTimepaymentStartTime=LocalDateTime.now();// 模拟支付处理逻辑try{Thread.sleep(2000);}catch(InterruptedExceptione){e.printStackTrace();}LocalDateTimepaymentEndTime=LocalDateTime.now();DurationprocessingDuration=Duration.between(paymentStartTime,paymentEndTime);System.out.println("支付处理耗时: "+processingDuration.getSeconds()+" 秒");}}

17. java8 - Duration 其他用法

重要知识点
  • Duration还可以进行时间间隔的加减操作,例如plus(Duration other)minus(Duration other)等。
代码示例
importjava.time.Duration;importjava.time.LocalDateTime;publicclassDeliveryEstimationService{publicvoidadjustDeliveryEstimation(){LocalDateTimeestimatedDeliveryTime=LocalDateTime.of(2025,2,25,10,0);Durationdelay=Duration.ofHours(2);LocalDateTimenewEstimatedDeliveryTime=estimatedDeliveryTime.plus(delay);System.out.println("原预计送达时间: "+estimatedDeliveryTime);System.out.println("调整后的预计送达时间: "+newEstimatedDeliveryTime);}}

18. java8 - DateTimeFormatter

重要知识点
  • 定义DateTimeFormatter用于格式化和解析日期时间对象,将日期时间对象转换为字符串,或将字符串转换为日期时间对象。
  • 创建方式
    • ofPattern(String pattern):根据指定的模式创建DateTimeFormatter
    • 提供了一些预定义的格式化器,如DateTimeFormatter.ISO_LOCAL_DATEDateTimeFormatter.ISO_LOCAL_TIME等。
  • 常用方法
    • format(TemporalAccessor temporal):将日期时间对象格式化为字符串。
    • parse(CharSequence text, TemporalQuery<T> query):将字符串解析为日期时间对象。
代码示例
importjava.time.LocalDate;importjava.time.format.DateTimeFormatter;publicclassOrderDateDisplayService{publicvoiddisplayOrderDate(){LocalDateorderDate=LocalDate.of(2025,2,24);DateTimeFormatterformatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");StringformattedDate=orderDate.format(formatter);System.out.println("订单日期: "+formattedDate);StringdateString="2025-03-15";LocalDateparsedDate=LocalDate.parse(dateString,formatter);System.out.println("解析后的日期: "+parsedDate);}}
http://www.cnnetsun.cn/news/3771904.html

相关文章:

  • PLM 软件选型指南推荐:Centric全维度评测指南
  • 银河麒麟SSH报错:服务器发送意外数据包(received:3, expected:20)排查实录
  • sm_90 / Hopper 架构硬件特性:TMA、异步 WGMMA、mbarrier、Thread Block Cluster,FA3 底层硬件基础
  • BGA 封装 表层粗糙度 (Surface Roughness)不良,白光干涉仪提升塑封材料 (Molding Material) 结合性能
  • 2026登报声明办理流程+渠道实测测评!流程、材料、费用对比
  • # 41号应用:呼吸引导 — 用动画引导心灵放松的 HarmonyOS 实践
  • 【AI术语避坑红宝书】:谷歌/微软/OpenAI内部术语对照表首次公开,含中英双语+使用场景+典型误用案例
  • Windows内存清理神器:3分钟让你的老旧电脑重获新生!
  • ROB101 Computational Linear Algebra:开启机器人学数学基础的终极指南
  • Path of Building技术架构深度解析:流放之路Build规划引擎的设计哲学
  • Afloat开发探秘:Objective-C运行时黑魔法与窗口管理原理
  • 运维实战分享|VMware NSX 4.2.4.0 全套官方镜像资源实操指南
  • 3种方法搞定Switch游戏安装:Awoo Installer终极指南
  • SwitchEmuModDownloader高级使用技巧:清除缓存、删除安装包与自定义Mod存放路径
  • OBS直播教程:OBS多路推流插件怎么用?OBS多路直播插件如何安装?
  • 终极Axure RP中文汉化指南:5分钟快速配置Axure 9/10/11完美中文界面
  • 如何快速构建专业后台管理系统:基于ThinkPHP6和Layui的完整解决方案
  • Vmware 虚拟机安装教程
  • 【单片机课设毕设项目】基于 STM32 的自习室 IC 卡权限管理及席位提示系统 单片机驱动的图书馆红外座位感应与自动门禁设计(015501)
  • 布列韦肽Hepcludex作用机制:靶向NTCP受体,从源头阻断HBV/HDV肝细胞入侵路径
  • Bevy设置系统架构设计与实现:基于反射的配置持久化技术
  • DCL 单例为何要 `volatile`:一次半初始化对象引发的血案
  • 大语言模型选型与实战指南:从GPT到开源部署全解析
  • 代码洁癖的工程价值重估:规范、工具与文化如何驱动前端质量
  • AI量化交易系统搭建全流程(含TensorFlow+Backtrader+Zipline工业级部署实录)
  • 算法与数据结构知识体系的完整拼图:7 月学习成果全景图
  • AI取代人类工作的5个临界点已出现:HR总监亲授3步职业免疫法(附2025技能缺口白皮书)
  • SQLite3绑定类型错误分析与修复:Duix-Avatar数据库操作优化方案
  • 体育数据API一站式接入|覆盖18+项目毫秒级响应
  • 3个简单秘诀:快速掌握Mermaid Live Editor免费在线图表工具