英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论