Search code examples
jsongroovy

Convert YYYY-MM-DD to CYYDDD using groovy


How do you convert a date in YYYY-MM-DD format to CYYDDD format using Groovy. For eg 2023-05-17 should return 123137. May 17th is the 137th day of 2023.

Thanks!


Solution

  • You could add a method to LocalDate to support this:

    import java.time.LocalDate
    import java.time.format.DateTimeFormatter
    
    LocalDate.metaClass.toCydd = {
        (delegate.year.intdiv(100) - 19) + delegate.format(DateTimeFormatter.ofPattern("yyDDD"))
    }
    
    String inputDate = "2023-05-17"
    
    String cyyddd = LocalDate.parse(inputDate).toCydd()
    assert cyyddd == '123137'
    

    Or if you don't want to add it to the metaClass, just use a static method:

    static String toCydd(LocalDate date) {
        (date.year.intdiv(100) - 19) + date.format(DateTimeFormatter.ofPattern("yyDDD"))
    }