gpt4 book ai didi

java - 如何删除日期(dd/mm/yyyy)中的年份(yyyy)

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:08 28 4
gpt4 key购买 nike

我有以下日期,

24/04/2019

13/05/2019

12/04/2019

我想删除年份并将这些日期转换为以下格式,

24/04

13/05

12/04

这不是仅用于输出我想在该日期执行加法或申请循环。

最佳答案

tl;dr

MonthDay                     // Represent a month & day-of-month, without a year.
.from( // Extract a `MonthDay` from a `LocalDate`, omitting the year but keeping the month and day-of-month.
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.parse( // Parse a string to get a `LocalDate`.
"24/04/2019" , // FYI, better to use standard ISO 8601 formats rather than devising a custom format such as this.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Match the formatting pattern of your input strings.
) // Returns a `LocalDate`.
) // Returns a `MonthDay`.
.format( // Generate a `String` with text representing the value of this `MonthDay` object.
DateTimeFormatter.ofPattern( "dd/MM" )
) // Returns a `String`.

查看此 code run live at IdeOne.com .

24/04

本地日期 & 月日

Java 内置了用于这项工作的类:

解析您的输入字符串以获取 LocalDate 对象。定义格式模式以匹配输入格式。

String input = "24/04/2019" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;

解析。

LocalDate ld = LocalDate.parse( input , f ) ;

生成标准字符串ISO 8601格式,YYYY-MM-DD。我强烈建议您在将日期时间值作为文本交换时使用这些格式,而不是设计您自己的自定义格式。

java.time 类在解析/生成字符串时默认使用这些标准格式。因此无需指定格式模式。

String output = ld.toString() ; 

2019-04-24

只提取月份和日期,忽略年份。

MonthDay md = MonthDay.from( ld ) ;  // Extract the month & day-of-month, but omit the year.

Generate a string采用标准 ISO 8601 格式。该格式在前面使用双连字符来指示缺少的年份。

String output = md.toString():

--04-24

你也可以解析这个值。

MonthDay md = MonthDay.parse( "--04-24" ) ;

您可以通过指定年份返回到 LocalDate

LocalDate ld = md.atYear( 2019 ) ;  // Generate a `LocalDate` by specifying a year to go with the month & day.

not for output only I want to perform addition or apply for loop on that date.

研究这两个类的 JavaDoc。提供了许多方便的方法。

您可以与isBeforeisAfter 进行比较。

您可以做数学运算,加减时间跨度。您可以进行调整,例如跳转到每月的特定日期。请注意,java.time 类遵循 immutable objects图案。因此,不是更改(“变异”)原始对象,而是使用基于原始对象的值创建第二个对象。


关于java.time

java.time框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧类 legacy日期时间类,例如 java.util.Date , Calendar , & SimpleDateFormat .

Joda-Time项目,现在在maintenance mode , 建议迁移到 java.time类。

要了解更多信息,请参阅 Oracle Tutorial .并在 Stack Overflow 中搜索许多示例和解释。规范为 JSR 310 .

您可以直接与您的数据库交换java.time 对象。使用 JDBC driver符合 JDBC 4.2或以后。不需要字符串,不需要 java.sql.* 类。

从哪里获得 java.time 类?

ThreeTen-Extra项目用附加类扩展 java.time。该项目是 future 可能添加到 java.time 的试验场。您可能会在这里找到一些有用的类,例如 Interval , YearWeek , YearQuarter , 和 more .

关于java - 如何删除日期(dd/mm/yyyy)中的年份(yyyy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54375721/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com