Search code examples
javakotlindatetimepathformatting

Format path with date placeholders


Is there a way to insert date parts into a path containing date formats? I've got an application that should save files into yearly & monthly folders, but I'd rather not hardcode it.

The current naming convention is this:

c:\reports\yyyy\MM_L_yyyy

which should result in:

c:\reports\2024\05_May_2024

I'd like to put this template into a config file and I thought about using regex to replace each date formattable placeholder from something like this:

c:\reports\{date:yyyy}\{date:MM_L_yyyy}

Would this be how you'd do it too or is there already a better solution for such cases?


Solution

  • It's easy with a templating engine. I picked PebbleTemplates. Here's an example:

    val sourceTemplate = "c:\\reports\\{{today | date(format='yyyy')}}\\{{today | date(format='MM_MMMM_yyyy')}}"
    val engine = PebbleEngine.Builder().build()
    val pebbleTemplate = engine.getLiteralTemplate(sourceTemplate)
    val writer: Writer = StringWriter()
    pebbleTemplate.evaluate(writer, mapOf("today" to LocalDate.now()))
    val result = writer.toString() // <-- c:\reports\2024\05_May_2024