Created
April 15, 2021 14:56
-
-
Save danslapman/ff6723a9903188d12baa8d185d93ef20 to your computer and use it in GitHub Desktop.
DateTimeFormatter interpolator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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