Convert YYYY-MM-DD to CYYDDD using groovy.

huangapple go评论95阅读模式
英文:

Convert YYYY-MM-DD to CYYDDD using groovy

问题

将YYYY-MM-DD格式的日期转换为CYYDDD格式的Groovy代码示例如下:

import java.text.SimpleDateFormat

def inputDate = "2023-05-17"
def sdf = new SimpleDateFormat("yyyy-MM-dd")
def date = sdf.parse(inputDate)
def cyyddd = (date.year % 100) * 1000 + date.dayOfYear

return cyyddd.toString()

这段代码将会把"2023-05-17"转换为"123137",其中123是年份的后两位(23),137是2023年的第137天。

英文:

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!

答案1

得分: 0

你可以为LocalDate添加一个方法来支持这个功能:

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'

或者如果你不想将其添加到metaClass中,可以使用一个静态方法:

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

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"))
}

</details>



huangapple
  • 本文由 发表于 2023年5月17日 23:06:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定