简体   繁体   English

如何在不将其转换为日期类型的情况下比较scala中的字符串日期

[英]How to compare string dates in scala without converting it into date type

I have two string dates我有两个字符串日期

a = '2021-05-23 b = '2021-04-24" a = '2021-05-23 b = '2021-04-24"

I'm trying to define a function that compares two string dates and returns true if b is one month greater than a.我正在尝试定义一个 function,它比较两个字符串日期并在 b 比 a 大一个月时返回 true。

Can anyone help me?谁能帮我?

Thanks谢谢

The question is a little bit unclear, like do you mean the difference would be EXACTLY one month?这个问题有点不清楚,比如你的意思是相差恰好是一个月? Or does the predicate hold for the input examples you provided just because 5 - 4 = 1 ?还是仅仅因为5 - 4 = 1 ,谓词就适用于您提供的输入示例? Anyway I think the code example below will give you the idea:无论如何,我认为下面的代码示例会给你一个想法:

import java.time.LocalDate

def isOneMonthGreater(dateString1: String, dateString2: String): Boolean = 
  (LocalDate.parse(dateString1).getMonthValue - LocalDate.parse(dateString2).getMonthValue) == 1

You can also use ChronoUnit :您还可以使用ChronoUnit

import java.time.LocalDate
import java.time.temporal.ChronoUnit

val d1 = LocalDate.parse("2022-05-23")
val d2 = LocalDate.parse("2022-04-24")
val d3 = LocalDate.parse("2022-04-23")

ChronoUnit.MONTHS.between(d2, d1)
// the above expression returns 0, since 29 days is actually 0 months!
ChronoUnit.MONTHS.between(d3, d1)
// this one returns 1

Also dates as strings is not a good practice most of the time, so having inputs of actual date types is more recommended.此外,大多数时候将日期作为字符串并不是一个好的做法,因此更建议输入实际日期类型。

Update:更新:


Without conversion to date, you can parse it manually and there are many many ways to do this.没有转换到最新,你可以手动解析它,有很多方法可以做到这一点。 And one thing to keep in mind is that as mentioned in comments, there might be some edge cases, but as far as I understood, this is just to explore around the language APIs.要记住的一件事是,如评论中所述,可能存在一些边缘情况,但据我所知,这只是围绕语言 API 进行探索。

  1. using regex.使用正则表达式。 You can define the format you're sure about for the date:您可以定义您确定的日期格式:
val pattern = "(\\d{4})-(\\d{2})-(\\d{2})".r
val dateString = "2022-03-02"

dateString match {
  case pattern(year, month, day) => ...
}

// or
val pattern(year, month, day) = dateString

But as mentioned, this is not safe, just to show that this approach exists.但是如前所述,这并不安全,只是为了表明存在这种方法。 2) splitting: 2)分裂:

dateString.split("-")

And you can deal with the array elements as you wish.您可以根据需要处理数组元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM