【问题标题】:Converting date from string to int in Java在Java中将日期从字符串转换为int
【发布时间】:2019-12-10 02:43:24
【问题描述】:

我想将一串日期值(1 月 27 日)转换为 01/27。我知道我可以使用 SimpleDateFormat 类或创建一堆 if-else 语句来做到这一点,但我想知道是否有另一种方法可以在不使用 SimpleDateFormat 类或创建 if-else 语句的情况下进行转换。

【问题讨论】:

  • 使用课程很容易,我可以使用它来完成,但我也想学习不同的方式。
  • 不仅有多种方法可以做到这一点,您想要的输出是String01/27不是int)。
  • “不使用 SimpleDateFormat 的转换方式” - 是的,使用 DateTimeFormatter - SimpleDateFormat 是时候死了
  • 您认为可以列出其他方式吗?您不必解释它们,我想自己研究它们,以便改进。是的,我的错误

标签: java string date int simpledateformat


【解决方案1】:

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

看到这个code run live at IdeOne.com

【讨论】:

  • sn24,如果需要号码,可以从monthDay.getMonthValue()monthDay.getDayOfMonth()获取。
猜你喜欢
  • 1970-01-01
  • 2012-04-14
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多