【问题标题】:Convert mediumDate() to other format (with Locale) on Joda-Time在 Joda-Time 上将 mediumDate() 转换为其他格式(使用区域设置)
【发布时间】:2014-08-14 01:57:01
【问题描述】:

我在 java 中转换其他格式的日期时遇到问题(我使用的是Joda-Time)。事实上,我有一个格式化的本地日期:

24/giu/14 (Italian format date...but other local formats are possible)

我想在输出中看到这个(使用 Locale 格式的日期):

24/06/2014

我尝试构建示例代码,但不起作用...我做错了什么?

public String DateConvertFromMediumFormatToSlash (String date)
    {
        DateTimeFormatter dtf = DateTimeFormat.mediumDate().withLocale(Locale.getDefault());
        LocalDate dt = dtf.parseLocalDate(date);

        return dt.toString(); // output: 2014-06-24
    }

【问题讨论】:

  • 您的问题令人困惑。你的输入到底是什么?您到底想要什么作为输出?

标签: java date datetime converter jodatime


【解决方案1】:

你的问题是关于你有什么作为输入和你想要什么作为输出的问题。

意大利使用连字符,而不是斜线

但一个问题似乎是斜线。 Joda-Time 需要连字符而不是斜线。下面是一些使用 Joda-Time 2.3 的示例代码,向您展示了 LocalDate 看起来像使用意大利语言环境的中等格式的字符串。

LocalDate localDate = new LocalDate( 2014, 6, 24 );
System.out.println( "localDate: " + localDate );

DateTimeFormatter formatter = DateTimeFormat.mediumDate().withLocale( Locale.ITALY );
System.out.println( "output: " + formatter.print( localDate ) );

运行时……

localDate: 2014-06-24
output: 24-giu-2014

为斜线定义格式化程序

因此,如果您想解析/生成带有斜杠而不是意大利语言环境预期的连字符的字符串,您必须明确定义这样的格式化程序。

String input = "24/giu/14";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "dd/MMM/yy").withLocale( Locale.ITALY );
LocalDate localDate = formatterInput.parseLocalDate( input );
System.out.println( "localDate: " + localDate );

DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "dd/MM/yy").withLocale( Locale.ITALY ); // Locale not needed here, but it's a good habit to specify.
String output = formatterOutput.print( localDate );
System.out.println( "Output: " + output );

运行时……

localDate: 2014-06-24
Output: 24/06/14

顺便说一句,使用两位数表示年份是自找麻烦。

【讨论】:

  • 好的!谢啦! :) 你说得对!但是,我不明白:如何根据语言环境设置输出模式?例如,意大利日期是 dd/MM/yy ...但是,例如,英文模式不一样...根据您的解决方案,我该如何管理?谢谢!! :)
  • @user3449772 您似乎忽略了我的整个答案。意大利日期是not dd/MM/yy。我的第三行代码准确显示了如何获取特定语言环境的格式。
  • 是的,对不起!因为我现在正在用智能手机阅读,所以我丢了一块!我认为这对我来说是最好的解决方案!谢啦!误会抱歉... :)
猜你喜欢
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2020-06-24
  • 2012-07-19
  • 1970-01-01
相关资源
最近更新 更多