Skip to content

Instantly share code, notes, and snippets.

@danslapman
Created April 15, 2021 14:56
Show Gist options
  • Save danslapman/ff6723a9903188d12baa8d185d93ef20 to your computer and use it in GitHub Desktop.
Save danslapman/ff6723a9903188d12baa8d185d93ef20 to your computer and use it in GitHub Desktop.
DateTimeFormatter interpolator
import $ivy.`com.propensive::contextual-core:3.0.1`
import java.time.format.DateTimeFormatter
import scala.language.experimental.macros
import contextual._
object dateTimeFormat {
object DateTimeFormatInterpolator extends Interpolator {
def contextualize(interpolation: StaticInterpolation): Seq[ContextType] = {
interpolation.parts.foreach {
case lit @ Literal(_, str) =>
try DateTimeFormatter.ofPattern(str) catch {
case ia: IllegalArgumentException =>
interpolation.error(lit, 0, ia.getMessage)
}
case hole @ Hole(_, _) =>
interpolation.abort(hole, "substitution is not supported")
}
Nil
}
def evaluate(interpolation: RuntimeInterpolation): DateTimeFormatter =
DateTimeFormatter.ofPattern(interpolation.parts.mkString)
}
implicit class ProtoStringContext(sc: StringContext) {
def dateTimeFormat(expressions: String*): DateTimeFormatter =
macro Macros.contextual[DateTimeFormatInterpolator.type]
}
}
@
import dateTimeFormat._
val fmt = dateTimeFormat"dd-MM-yyyy"
println(fmt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment