I want to convert a string of date value(January 27) to 01/27. I know I can do this using the SimpleDateFormat class or creating a bunch of if-else statements, but I was wondering if there was another way to convert it without using the SimpleDateFormat class or creating if-else statements.
MonthDay
.parse(
"January 27" ,
DateTimeFormatter.ofPattern( "MMMM d").withLocale( Locale.US )
)
.format(
DateTimeFormatter.ofPattern( "MM/dd")
)
MonthDay
There is a class for that: MonthDay
.
Parse a standard ISO 8601 string.
String input = "--01-23" ;
MonthDay monthDay = MonthDay.parse( input ) ;
Generate text in standard format.
String output = MonthDay.toString() ;
For your custom format, define a custom formatting pattern with DateTimeFormatter
class.
MonthDay md = MonthDay.parse( "--01-23" ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd") ;
String output = md.format( f ) ;
01/23
See this code run live at IdeOne.com .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.