Search code examples
scaladatesimpledateformat

Convert Date String to Day in Scala


I have a Date String

val ts = "2020-02-05 15:12:01-0800"

I need to get the value till of last day of week. i.e 2020-02-08

This is what I did till now using SimpleDateFormat

val DATE_FORMAT = "yyyy-MM-dd HH:mm:ssZ"
val ts = "2020-02-05 15:12:01-0800"
val date = df.parse(ts)

val Cal =Calendar.getInstance()
Cal.set (Calendar.DAY_OF_WEEK, Calendar.SATURDAY)
Cal.setTime(date)

val LastDayOfWeek=DATE_FORMAT.format (Cal.getTime ())

However it is returning "2020-02-05 15:12:01-0800"


Solution

  • SimpleDate is pretty old and outdated. Here's a solution with the current java.time.LocalDate library.

    import java.time.{LocalDate,DayOfWeek}
    
    val ts = "2020-02-05 15:12:01-0800"
    val ld = LocalDate.parse(ts take 10)
    val saturday = ld.plusDays(DayOfWeek.SATURDAY.getValue()
                               - ld.getDayOfWeek().getValue())
    //saturday: java.time.LocalDate = 2020-02-08
    

    Note that if the ts date is a Sunday then saturday will be the day before.