Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Scala是关于字符串的操作_String_Scala_Date_Substr - Fatal编程技术网

String Scala是关于字符串的操作

String Scala是关于字符串的操作,string,scala,date,substr,String,Scala,Date,Substr,如果我有如下字符串: "2018013108","2018013107","2018020100","2018013119","2018013114".... 每个字符串的最后2个元素表示小时。我想得到这样一个函数:他可以使时间提前一小时并输入。例如: "2018013108" will change to "2018013107","2018020100" will change to "2018013123"... 这种一小时的转换只在一年内发生,因此提前一小时只需要注意月和日期的转换。

如果我有如下字符串:

"2018013108","2018013107","2018020100","2018013119","2018013114"....
每个字符串的最后2个元素表示小时。我想得到这样一个函数:他可以使时间提前一小时并输入。例如:

"2018013108" will change to "2018013107","2018020100" will change to "2018013123"...
这种一小时的转换只在一年内发生,因此提前一小时只需要注意月和日期的转换。我应该如何编码?谢谢

使用最后2个字符获取小时数 如果当前小时数不是00,则将小时数减-1,否则之前的小时数为23 然后这些天将是前一天或前一个月的最后一天,根据今天是哪一天

您可以维护的地图以获取上个月的最后一天

下面是它的样子

import org.scalatest.FunSpec

class SubstractDateSpec extends FunSpec {

  val monthDays = Map(
    1 -> 31,
    2 -> 28,
    3 -> 31,
    4 -> 30,
    5 -> 31,
    6 -> 30,
    7 -> 31,
    8 -> 31,
    9 -> 30,
    10 -> 31,
    11 -> 31,
    12 -> 31
  )

  def formatIt(data: Int): String = {
    if (data < 10) "0" + data
    else data + ""
  }

  def format(date: String): String = {

    val year = date.slice(0, 4)
    val month = date.slice(4, 6)
    val days = date.slice(6, 8)
    val hours = date.takeRight(2).toInt

    if (hours == 0 && days.toInt == 1) {
      val newMonth = month.toInt - 1
      val newDay = monthDays(newMonth)
      year + formatIt(newMonth) + formatIt(newDay) + "23"

    } else if (hours == 0) {
      year + month + formatIt(days.toInt - 1) + "23"

    } else {
      year + month + days + formatIt(hours - 1)
    }
  }

  it("date") {
    assert(format("2018013108") == "2018013107")
    assert(format("2018101000") == "2018100923")

    assert(format("2018020100") == "2018013123")
  }

}
了解
您应该如何编写代码?你打开你最好的编辑器或IDE,开始写东西。请看一看。这不是一个代码服务,您至少必须展示您的努力。您不需要spark来解决此解决方案。我展示的例子是纯scala和scalatest。但显然,这段代码在spark内部也能正常工作