【问题标题】:JodaTime date formatting issueJodaTime 日期格式问题
【发布时间】:2011-05-24 16:36:04
【问题描述】:

我的日期格式如下:

String inputDateString = aMessage.getString("updated_at");
                        DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();

                        DateTime date = fmt.parseDateTime(inputDateString);
                        DateTime now = new DateTime();
                        Period period = new Period(date, now);

                        PeriodFormatter formatter = new PeriodFormatterBuilder()
                            .appendSeconds().appendSuffix(" seconds ago\n")
                            .printZeroNever()
                            .toFormatter();

                        String elapsed = formatter.print(period);

                        dateTextView.setText(elapsed);

我希望能够展示:

3 seconds ago if the period is less than 60 seconds
3 minutes ago if the period is less than 60 minutes
3 hours ago is the period is less than X hours
3 days ago if the period is less than X days 

等等。等等

我怎样才能做到这一点?

【问题讨论】:

    标签: java datetime date time jodatime


    【解决方案1】:

    查看Period 上可用的方法,尤其是toStandardSeconds() 等方法。使用这些应该很容易通过一些 if-else 语句进行测试来实现您所追求的目标,例如

    if (period.toStandardSeconds().getSeconds() < 60) {
       // form second-based string
    }
    else if (period.toStandardMinutes().getMinutes() < 60) {
       // ...
    

    我认为PeriodFormatter 在这种情况下是一个红鲱鱼,因为我认为不可能构建一个可以满足您需求的单一格式化程序 - 而在 if 块中您可以只获得秒数/小时/等。直接使用与条件相同的方法调用。

    【讨论】:

    • 似乎我无法将它与 int 进行比较。我收到编译时错误The operator &lt; is undefined for the argument type(s) Minutes, int
    • 您认为org.joda.time.Minutes 的实例是否代表少于60 分钟?看看API,看看你能不能自己解决(不难)!
    【解决方案2】:

    您可以通过一系列if 语句轻松实现此目的。如果这些都是您的全部要求,您甚至可以考虑取消PeriodFormatter 并直接从Period 提取相关数据(通过toStandardSeconds() 等)。

    您当然可以使用period.toStandardSeconds() 等来决定使用哪种格式。

    【讨论】:

      猜你喜欢
      • 2013-07-01
      • 2012-12-07
      • 1970-01-01
      • 2011-09-20
      • 2014-04-01
      相关资源
      最近更新 更多