gpt4 book ai didi

Java 检查一个月中的天数并添加缺少的日期

转载 作者:行者123 更新时间:2023-12-02 00:39:07 25 4
gpt4 key购买 nike

嗨,我有以下日期数组列表

["2010-08-01","2010-08-02","2010-08-04","2010-08-05","2010-08-06","2010-08-07 ","2010-08-08","2010-08-09","2010-08-11","2010-08-12","2010-08-13","2010-08-14", "2010-08-15","2010-08-17","2010-08-18","2010-08-20","2010-08-21","2010-08-26","2010 -08-28","2010-08-29"]

我有两个想要实现的目标,

1)如何根据上面的年月获取每个月的天数?2)如何为上面的整个日期字符串序列添加缺失的日期(与上面的格式相同)?例如:2010-08-01,2010-08-02,2010-08-04 -->我应该在2010-08-02和2010-08-04之间添加2010-08-03

谢谢!

最佳答案

最简单的方法是解析所有日期以查找最大值和最小值。然后生成最小和最大日期之间的所有日期的列表。

public static void main(String... args) throws ParseException {
String[] dates = { "2010-08-01","2010-09-02","2010-07-28","2010-08-29" };
String[] dates2 = fillInDates(dates, "yyyy-MM-dd");
System.out.println(Arrays.toString(dates2));
}

private static final long MILLIS_PER_DAY = 24L * 3600 * 1000;

private static String[] fillInDates(String[] dates, String format) throws ParseException {
if (dates == null || dates.length < 1) return dates;

SimpleDateFormat sdf = new SimpleDateFormat(format);
long min = Long.MAX_VALUE, max = Long.MIN_VALUE;
for (String date : dates) {
long time = sdf.parse(date).getTime();
if(min > time) min = time;
if(max < time) max = time;
}
String[] dates2 = new String[(int) ((max - min)/MILLIS_PER_DAY+1)];
for(int i=0;i<dates2.length;i++)
dates2[i] = sdf.format(new Date(min + i * MILLIS_PER_DAY));
return dates2;
}

打印

[2010-07-28、2010-07-29、2010-07-30、2010-07-31、2010-08-01、2010-08-02、2010-08-03、2010-08- 04, 2010-08-05, 2010-08-06, 2010-08-07, 2010-08-08, 2010-08-09, 2010-08-10, 2010-08-11, 2010-08-12, 2010-08-13, 2010-08-14, 2010-08-15, 2010-08-16, 2010-08-17, 2010-08-18, 2010-08-19, 2010-08-20, 2010- 08-21, 2010-08-22, 2010-08-23, 2010-08-24, 2010-08-25, 2010-08-26, 2010-08-27, 2010-08-28, 2010-08- 29, 2010-08-30, 2010-08-31, 2010-09-01, 2010-09-02]

关于Java 检查一个月中的天数并添加缺少的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6882172/

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