Search code examples
scalaformattinglocaldate

Scala f interpolator formatting for Java LocalDate


I'd like to be able to format strings based on Java.LocalDate using the f interpolator, i.e. something like:

val  = LocalDate.of(2024,7,28)

f"$dt:YYYY-MM-dd"

But this will give a compile error with an invalid formatter. I can do this explicitly like this:

import java.time.format.DateTimeFormatter

val dt = LocalDate.of(2024,7,28)

f"${dt.format(DateTimeFormatter.ofPattern("YYYY-MM-dd"))}"

I know there is a way to write a custom interpolator formatter but can't work out to make this work for LocalDate. Does anyone have an example?

Thanks,

David


Solution

  • import java.time.*
    
    val dt = LocalDate.of(2024,7,28).toEpochDay()
    
    //f"${dt}%tY-%tm-%td"
    f"$dt%tY"
    
    "%tY-%1$tm-%1$td".format(dt)
    
    f"$dt%tY-$dt%tm-$dt%td"
    
    

    https://scastie.scala-lang.org/4wXYGG1vSIempOMPMUqXTA

    This works as well:

    f"$dt%tY"
    

    What doesn't work are multiples formats following the same value, also f"$dt%1$tY" is not supported.

    Use this instead:

    "%tY-%1$tm-%1$td".format(dt)
    

    Also note the suffix .toEpochDay(). Without it it's going to fail to compile because that type is not supported.