Scala-关于String的操作
Scala-the operation about the String
如果我有这样的字符串:
"2018013108","2018013107","2018020100","2018013119","2018013114"....
每个String的最后2个元素代表hours.I想得到这样一个功能:他可以让时间提前一小时input.For例子:
"2018013108" will change to "2018013107","2018020100" will change to "2018013123"...
这个一小时的班次只发生在一年之内,所以提前一小时只需要注意月份的转换,dates.How我应该编码吗?谢谢!!!
- 取最后 2 个字符得到小时数
- 如果当前时间不是
00
,则用 -1
减去时间,否则您之前的时间将是 23
然后根据今天是哪一天,日期将是前一天或前一个月的最后一天。
您可以维护一个 "month to end of days" 的映射以获取上个月的最后一天
这是它的样子;
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")
}
}
了解
如果我有这样的字符串:
"2018013108","2018013107","2018020100","2018013119","2018013114"....
每个String的最后2个元素代表hours.I想得到这样一个功能:他可以让时间提前一小时input.For例子:
"2018013108" will change to "2018013107","2018020100" will change to "2018013123"...
这个一小时的班次只发生在一年之内,所以提前一小时只需要注意月份的转换,dates.How我应该编码吗?谢谢!!!
- 取最后 2 个字符得到小时数
- 如果当前时间不是
00
,则用-1
减去时间,否则您之前的时间将是23
然后根据今天是哪一天,日期将是前一天或前一个月的最后一天。
您可以维护一个 "month to end of days" 的映射以获取上个月的最后一天
这是它的样子;
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")
}
}