我想将Joda LocalDateTime格式化为yDDD格式,其中"y"不是代表整个年份,而是代表十年中的年份的一个个位数,DDD代表一年中的一天。似乎"yDDD"作为格式字符串正确地将DDD解释为"一年中的某一天",但不是打印年份的单个字符,而是打印整个4位数字的年份。如何使用年份的最后一个数字来格式化Joda LocalDateTime ?
例如,2021年2月1日将表示为1032:
- 十年第1年
1
- 每年第32天的
032
这是使用java日期api,但它应该很容易转移到joda:
@Test
public void testDateFormat() {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("DDD");
ZonedDateTime date = ZonedDateTime.now();
System.out.println("formatted: " + (date.getYear() % 10) + date.format(fmt));
}
它产生:
formatted: 1050
java。时间和日期formatterbuilder . appendvaluereduced ()
据我所知,Joda-Time不能做你想做的事。java。time是现代Java日期和时间API,从Java 8开始取代了Joda-Time。通过这个格式化程序:
private static final DateTimeFormatter ydddFormatter = new DateTimeFormatterBuilder()
.appendValueReduced(ChronoField.YEAR, 1, 1, LocalDate.of(2020, Month.JANUARY, 1))
.appendPattern("DDD")
.toFormatter();
来演示:
LocalDate sampleDate = LocalDate.of(2021, Month.FEBRUARY, 1);
String formattedDate = sampleDate.format(ydddFormatter);
System.out.println(formattedDate);
输出:1032年appendValueReduced
方法特别用于打印和解析2位数的年份,但是我们没有理由不能将它用于1位数的年份。对于固定宽度的1位年份字段,仅为width
和maxWidth
传递1。
appendValueReduced
的最后一个参数,即我代码中的LocalDate
,是在解析时解释1位数年份的基准日期。对于格式化,它被忽略,但它仍然需要在那里。
Joda-Time和String.format()
如果你的日期必须来自Joda-Time,而你现在没有升级,那么在格式化时你需要使用其他方法而不是Joda-Time(就像其他答案一样)。对于一个简单的解决方案,我的建议是在String.format()
上全力以赴:
LocalDateTime dateTime = new LocalDateTime(2021, 2, 1, 23, 45);
String ydddString = String.format(Locale.US, "%01d%03d",
dateTime.getYear() % 10, dateTime.getDayOfYear());
assert ydddString.length() == 4 : ydddString;
System.out.println(ydddString);
1032年java.time
Joda-Time项目现在处于维护模式。它的创造者,Stephen Colebourne,继续创造了它的替代品,java。time类内置于Java 8及以后的版本中。
我没有找到一种方法来做你想只用一个格式化器对象。然而,奥莱·V.V.确实找到了另一个答案。我推荐这个解决方案。
在我的方法中,写一个方法来做一些字符串操作,或者使用Erik在Answer中所示的数学。
LocalDate ld = LocalDate.of( 2021 , 1 , 1 ) ;
String yyyy = Integer.toString( ld.getYear() ) ; // Get the number of the year as text.
String y = yyyy.substring( yyyy.length() - 1 ) ; // Pull last character of that year-as-text to get single-digit year of decade.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "DDD" ) ; // Get day-of-year, 1-365 or 1-366.
String output = y + ld.format( f ) ;
System.out.println( output ) ;
查看此代码运行在IdeOne.com。
1001年<标题>ISO 8601 h1> 建议使用ISO 8601定义的标准格式:四位数的年份,连字符,三位数的年月日。
所以,2021-01-01是2021-001
。
LocalDate.now().format( DateTimeFormatter.ISO_ORDINAL_DATE )
标题>