JAVA:如何计算多个字符串日期的平均天数?

我编写了一个程序,它总是计算两个日期之间的天数差异。我现在想总结所有差异天数,并将其除以计数,以便得到平均天数。有人能帮我吗?有没有办法甚至避免 for 循环。


import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;


public class AVGDateCalculation {

    public static void main (String [] args) throws ParseException{

    String formatted =

            "2014-04-28 ,2014-04-28 ,"

            + "2015-10-26 ,2015-10-30 ,"

            + "2015-07-30 ,2015-07-30 ,"

            + "2015-04-14 ,2015-04-20 ,"

            + "2013-11-14 ,2013-11-18 ,"

            + "2014-04-16 ,2014-04-22 ,"

            + "2014-11-19 ,2014-11-21 ,"

            + "2019-10-01 ,2019-10-01 ";


                String[] parts = formatted.split(",");


                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                int count = 0;

                int a;

                long difference = 0L;

                float daysBetween = 0.00f;

                float averageDays = 0.00f;

                Date dateBefore = null;

                Date dateAfter = null;

                for (a = 0; a<parts.length; a+=1) {

                    dateBefore = sdf.parse(parts[a++]);

                    count++;

                    dateAfter = sdf.parse(parts[a+=0]);

                    difference = dateAfter.getTime() - dateBefore.getTime();

                    daysBetween = (difference / (1000*60*60*24));    

                    averageDays = (count / daysBetween);


                    System.out.println(String.valueOf(dateAfter) + " - " + `String.valueOf(dateBefore));`

                    System.out.println(String.valueOf(dateAfter.getTime()) + " - " + String.valueOf(dateBefore.getTime()));

                    System.out.println(String.valueOf(daysBetween));

                    System.out.println(String.valueOf(averageDays) + " days");

                    System.out.println(String.valueOf(count));

                }


    }

}


PIPIONE
浏览 109回答 2
2回答

江户川乱折腾

我宁愿使用LocalDate而不是SimpleDateFormat,因为在那里你可以更轻松地计算差异和许多其他事情。要分割成对出现的日期,您可以使用正则表达式在每隔一个逗号分隔字符串。import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoUnit;import java.util.LongSummaryStatistics;import java.util.function.Function;import java.util.regex.Pattern;public class Test{&nbsp; &nbsp; public static void main(String[] args){&nbsp; &nbsp; &nbsp; &nbsp; String formatted&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = "2014-04-28 ,2014-04-28 ,"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "2015-10-26 ,2015-10-30 ,"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "2015-07-30 ,2015-07-30 ,"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "2015-04-14 ,2015-04-20 ,"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "2013-11-14 ,2013-11-18 ,"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "2014-04-16 ,2014-04-22 ,"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "2014-11-19 ,2014-11-21 ,"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; + "2019-10-01 ,2019-10-01 ";&nbsp; &nbsp; &nbsp; &nbsp; //a formater for your date pattern&nbsp; &nbsp; &nbsp; &nbsp; DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");&nbsp; &nbsp; &nbsp; &nbsp; //a function to calculate the date differnce for a given pair of dates of form "2014-04-28 ,2014-04-28"&nbsp; &nbsp; &nbsp; &nbsp; Function<String,Long> dateDiff = s ->&nbsp; ChronoUnit.DAYS.between(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LocalDate.parse(s.split(",")[0].trim(), dtf),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LocalDate.parse(s.split(",")[1].trim(), dtf));&nbsp; &nbsp; &nbsp; &nbsp; //split your original string at each second ',' with below regex&nbsp; &nbsp; &nbsp; &nbsp; LongSummaryStatistics statistics = Pattern.compile("(?<!\\G[\\d -]+),")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .splitAsStream(formatted)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToLong(s -> dateDiff.apply(s))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .summaryStatistics();&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(statistics);&nbsp; &nbsp; }}统计数据包含总和、计数、最小值、最大值和平均值。如果你只对平均值感兴趣,也可以直接调用&nbsp; &nbsp; double average = Pattern.compile("(?<!\\G[\\d -]+),")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .splitAsStream(formatted)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToLong(s -> dateDiff.apply(s))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .average().getAsDouble();&nbsp;

哈士奇WWW

博士ChronoUnit                               // An enum delineating granularities of time..DAYS                                    // `DAYS` is one of the objects pre-defined on that enum..between(                                // Calculates elapsed time.    LocalDate.parse( "2015-10-26" ) ,    // `LocalDate` represents a date-only value, without time-of-day, without time zone.    LocalDate.parse( "2015-10-30" )      // `LocalDate` by default parses strings that comply with standard ISO 8601 formats.)                                        // Returns a `long`, the number of days elapsed. Uses Half-Open approach, where the beginning is *inclusive* while the ending is *exclusive*. 4错误的班级该类java.util.Date代表 UTC 中的某个时刻,而不是日期。此外,那个可怕的类在几年前就被现代的java.time类取代了。LocalDate该类LocalDate表示仅日期值,没有时间、时区或相对于 UTC 的偏移量。您的输入符合 ISO 8601,因此您可以直接解析。无需定义格式化模式。LocalDate start = LocalDate.parse( "2015-10-26" ) ;使用 计算经过的时间Period。Period p = Period.of( start , stop ) ;或者直接询问天数。long days = ChronoUnit.DAYS.between( start , stop ) ;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java