2 回答

TA貢獻1851條經驗 獲得超5個贊
我寧愿使用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{
public static void main(String[] args){
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 ";
//a formater for your date pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//a function to calculate the date differnce for a given pair of dates of form "2014-04-28 ,2014-04-28"
Function<String,Long> dateDiff = s -> ChronoUnit.DAYS.between(
LocalDate.parse(s.split(",")[0].trim(), dtf),
LocalDate.parse(s.split(",")[1].trim(), dtf));
//split your original string at each second ',' with below regex
LongSummaryStatistics statistics = Pattern.compile("(?<!\\G[\\d -]+),")
.splitAsStream(formatted)
.mapToLong(s -> dateDiff.apply(s))
.summaryStatistics();
System.out.println(statistics);
}
}
統計數據包含總和、計數、最小值、最大值和平均值。如果你只對平均值感興趣,也可以直接調用
double average = Pattern.compile("(?<!\\G[\\d -]+),")
.splitAsStream(formatted)
.mapToLong(s -> dateDiff.apply(s))
.average().getAsDouble();

TA貢獻1799條經驗 獲得超6個贊
博士
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?)?;
添加回答
舉報