gpt4 book ai didi

java - 减去和比较日期

转载 作者:行者123 更新时间:2023-11-29 06:41:41 25 4
gpt4 key购买 nike

我在 SO 上找到了一些类似的问题,但没有找到解决方案。

我今天的 Date 如下:(假设为 Date1,它的值为 2012-06-22)

    Calendar cal = Calendar.getInstance();
SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
Date start = cal.getTime();
String currentDate=dateformatter.format(start);

我正在从用户那里检索 4 个值:

  • 特定日期(假设 5)
  • 特定月份(假设 1)
  • 特定年份(假设 2012)
  • 没有。天数(假设 7)

所以这个日期,比如说 Date2 变成了 2012-01-05 (yyyy-MM-dd) 和 No.天数 设置为 7


我想比较日期 1日期 2-No.天数

我知道通过使用以下代码段,特别是没有。可以从日历实例中减去天数。

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -7);

但是因为我有 Date2 形式的 String,所以我无法遵循这种方法。

感谢任何帮助。

编辑:

根据您的建议,我可以使用 SimpleDateFormatparse 方法将 String 转换为 Date >.

现在我有 2 个 Date 对象。

  • 如何找到它们之间在方面的差异?<
  • 如何减去特定的号码。天数,比如 7,从特定日期开始,比如 2012-01-05?

最佳答案

java.time

问题和已接受的答案使用了 java.util Date-Time API 及其解析/格式化 API,SimpleDateFormat 这是使用标准的适当做法库于 2012 年。2014 年 3 月,Java 8 引入了 modern Date-Time API它取代了遗留 API,从那时起强烈建议使用现代日期时间 API。

此外,下面引用的是来自 home page of Joda-Time 的通知:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

从您的问题中复制的要求:

From your suggestions, I'll be able to convert String to Date by usingparse method of SimpleDateFormat.

Now I've 2 Date Objects.

  • How do I find Difference between them in terms of days, months, andyears?
  • How to Subtract particular no. of days, say 7, from aparticular date, say 2012-01-05?

使用现代日期时间 API java.time 的解决方案:

使用 java.time,您可以将日期字符串解析为 LocalDate,然后找到 Period在此日期和当前日期(您使用 LocalDate.now() 获得)之间。您还可以使用 minusXxx/minus 等方法减去天、月和年。您有类似的方法 (plusXxx/plus) 来添加这些单元。检查the documentation of LocalDate了解更多信息。

注意:java.time API 基于ISO 8601因此,您不需要 DateTimeFormatter 来解析已经采用 ISO 8601 格式的日期时间字符串(例如,您的日期时间字符串 2012-06-22) .

演示:

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

class Main {
public static void main(String[] args) {
LocalDate then = LocalDate.parse("2012-06-22");
LocalDate now = LocalDate.now();

Period period = Period.between(then, now);
System.out.println(period);
System.out.printf("%d years %d months %d days%n",
period.getYears(), period.getMonths(), period.getDays());

// Examples of subtracting date units
LocalDate sevenDaysAgo = now.minusDays(7);
System.out.println(sevenDaysAgo);
// Alternatively
sevenDaysAgo = now.minus(7, ChronoUnit.DAYS);
System.out.println(sevenDaysAgo);
}
}

示例运行的输出:

P10Y6M27D
10 years 6 months 27 days
2023-01-11
2023-01-11

ONLINE DEMO

Trail: Date Time 了解有关现代日期时间 API 的更多信息.

关于java - 减去和比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11152851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com