簡體   English   中英

在Java中將日期從字符串轉換為int

[英]Converting date from string to int in Java

我想將一串日期值(1 月 27 日)轉換為 01/27。 我知道我可以使用 SimpleDateFormat 類或創建一堆 if-else 語句來做到這一點,但我想知道是否有另一種方法可以在不使用 SimpleDateFormat 類或創建 if-else 語句的情況下轉換它。

tl;博士

MonthDay
.parse(
    "January 27" ,
    DateTimeFormatter.ofPattern( "MMMM d").withLocale( Locale.US )
)
.format(
    DateTimeFormatter.ofPattern( "MM/dd") 
)

MonthDay

有一個類: MonthDay

解析標准 ISO 8601 字符串。

String input = "--01-23" ;
MonthDay monthDay = MonthDay.parse( input ) ;

以標准格式生成文本。

String output = MonthDay.toString() ;

對於您的自定義格式,請使用DateTimeFormatter類定義自定義格式模式。

MonthDay md = MonthDay.parse( "--01-23" ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd") ;
String output = md.format( f ) ;

01/23

查看此代碼在 IdeOne.com 上實時運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM