Search code examples
stringscaladatesubstr

Scala-the operation about the String


If I have some Strings like this :

"2018013108","2018013107","2018020100","2018013119","2018013114"....

the last 2 elements of each String represent hours.I want to get such a function: he can make the time one hour earlier and input.For example:

"2018013108" will change to "2018013107","2018020100" will change to "2018013123"...

This one hour shift takes place only within a year, so one hour ahead of time only requires attention to the conversion of months and dates.How should I code? Thx!!!


Solution

    • take last 2 characters to get hours
    • substract hours by -1 if current hours is not 00 else your earlier hours will be 23
    • and then the days would be a day before or the last day of earlier month based on which day is today.

    • you can maintain a map of "month to end of days" to get the last day of previous month

    Here's how it would look like;

    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")
      }
    
    }
    

    Read about

    scala.String

    scala.collection.immutable.Map