2016-07-27 76 views
-1

如何获取两个日期之间的日期?如何确定日期是否在Scala中的两个日期之间如何才能确定

这是我的日期:

val date = "01 Jan, 2015" 

日期范围:

val dateFrom = "01 Jan, 1970" 
val dateTill = "01 Jan, 2016" 

我想检查我的日期是日期范围之间。

这是我尝试:

def getLocalDate(date: String): LocalDate = { 

    LocalDate.parse(date, format.DateTimeFormatter.ofPattern("dd MMM, yyyy")) 
} 

def isDateBetWeenRange(from: String, till: String, date: String): Boolean = { 

    val fromDate = getLocalDate(from) 
    val tillDate = getLocalDate(till) 
    val myDate = getLocalDate(date) 

    myDate.isBefore(tillDate) && myDate.isAfter(fromDate) 
} 

不过是情况的日期是相同直到日期这将返回false:

val date = "01 Jan, 2010" 
println(isDateBetWeenRange("01 Jan, 2000", "01 Jan, 2016", "01 Jan, date)) 
+0

,更换'X isBefore y'用'!(x isAfter y)'和类似的其他条件。 –

回答

0

那么漂亮和Scala的方式来添加一些行为会是添加的隐式类LocalDate

例如:

现在
implicit class SLocalDate(val time: LocalDate) { 
    def isBeforeEq(other: ChronoLocalDate) = !time.isAfter(other) 
    def isAfterEq(other: ChronoLocalDate) = !time.isBefore(other) 
} 

,在这种隐含的范围,你可以改变你的测试:

myDate.isBeforeEq(tillDate) && myDate.isAfterEq(fromDate) 
0

您可以调整功能:如果你要包容范围

(myDate.isBefore(tillDate) && myDate.isAfter(fromDate)) || 
    myDate.isEqual(tillDate) || 
    myDate.isEqual(fromDate)