[英]How to Remove year(yyyy) in date(dd/mm/yyyy)
我有以下日期,
24/04/2019
13/05/2019
12/04/2019
我想刪除年份並將這些日期轉換為以下格式,
24/04
13/05
12/04
這不僅僅用於輸出我想在該日期執行添加或申請循環。
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`.
請參閱IdeOne.com上的此代碼 。
24/04
LocalDate
和MonthDay
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年4月24日
只提取月份和日期,而忽略年份。
MonthDay md = MonthDay.from( ld ) ; // Extract the month & day-of-month, but omit the year.
生成標准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.
不僅僅是輸出我想在那個日期執行添加或申請循環。
研究這兩個類的JavaDoc。 提供了許多方便的方法。
您可以與isBefore
和isAfter
進行比較。
您可以進行數學運算,添加或減去時間跨度。 您可以進行調整,例如跳轉到特定的某個日期。 請注意, java.time類遵循不可變對象模式。 因此,不是更改(“改變”)原始對象,而是使用基於原始值的值創建第二個對象。
java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊遺留日期時間類,如java.util.Date
, Calendar
和SimpleDateFormat
。
現在處於維護模式的Joda-Time項目建議遷移到java.time類。
要了解更多信息,請參閱Oracle教程 。 並搜索Stack Overflow以獲取許多示例和解釋。 規范是JSR 310 。
您可以直接與數據庫交換java.time對象。 使用符合JDBC 4.2或更高版本的JDBC驅動程序 。 不需要字符串,不需要java.sql.*
類。
從哪里獲取java.time類?
ThreeTen-Extra項目使用其他類擴展了java.time。 該項目是未來可能添加到java.time的試驗場。 您可以在這里找到一些有用的類,比如Interval
, YearWeek
, YearQuarter
,和更多 。
您可以從索引0到4獲取子字符串:
String input = "24/04/2019";
String output = input.substring(0, 5);
用這個:
String input = "24/04/2019";
String output = input.substring(0,input.lastIndexOf("/"));
您也可以嘗試使用字符串拆分邏輯,如下所示。
String date="24/04/2019";
String [ ] ddyymm=date.split("/");
String output=ddyymm[0]+"/"+ddmmyy[1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.