java.util.Date

编程入门 行业动态 更新时间:2024-10-23 13:33:12
本文介绍了java.util.Date - 从日期删除三个月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的日期类型为 java.util.Date

我想从中减去三个月。

在API中没有找到很多乐趣。

Not finding a lot of joy in the API.

推荐答案

这是普通的 JDK 版本,它需要 Calendar 类作为帮助:

Here's the plain JDK version, it needs the Calendar class as a helper:

Date referenceDate = new Date(); Calendar c = Calendar.getInstance(); c.setTime(referenceDate); c.add(Calendar.MONTH, -3); return c.getTime();

但你应该认真考虑使用 Joda图书馆 ,因为日期和日历类。使用Joda,您可以执行以下操作:

But you should seriously consider using the Joda library, because of various shortcomings of the Date and Calendar classes. With Joda you can do the following:

new DateTime().minusMonths(3).toDate();

或者如果你想减去给定日期而不是当前日期:

Or if you want to subtract from a given date instead of the current:

new DateTime(referenceDate).minusMonths(3).toDate();

Java 8更新:对于Java 8,您还可以使用新的JSR 310 API(受Joda启发):

Update for Java 8: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda):

LocalDateTime.from(referenceDate.toInstant()).minusMonths(3);

更多推荐

java.util.Date

本文发布于:2023-10-16 00:21:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1495916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:java   util   Date

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!