JodaTime 日期格式问题
我正在按如下方式格式化我的日期:
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
等等。
我怎样才能实现这一点?
I am formatting my date as follows:
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);
I would like to be able to show:
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
etc. etc.
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 Period 上提供的方法,特别是诸如
toStandardSeconds()
之类的。使用这些应该很容易通过一些if-else
语句进行测试来实现您想要的目标,例如我认为
PeriodFormatter
在这种情况下是一个红鲱鱼,因为我认为不可能构建一个可以完成您想要的操作的格式化程序 - 并且在if
块中您只能获取秒/小时/等。直接使用与条件语句中相同的方法调用。Have a look at the methods available on Period, in particular those such as
toStandardSeconds()
. Using these it should be straightforward to achieve what you're after with a fewif-else
statements making tests such asI think the
PeriodFormatter
is a red herring in this case, as I don't think it's possible to construct a single formatter that does what you want - and in theif
blocks you can just get the seconds/hours/etc. directly using the same method calls as in the conditionals.您可以通过一系列
if
语句轻松实现此目的。如果这些是您的全部要求,您甚至可以考虑取消PeriodFormatter
并直接从Period
中提取相关数据(通过toStandardSeconds()
等)。您当然可以使用 period.toStandardSeconds() 等来决定使用哪种格式。
You can easily achieve this with a series of
if
statements. If these are your requirements in their entirety, you might even consider doing away withPeriodFormatter
and extracting the relevant data directly fromPeriod
(viatoStandardSeconds()
et al).You can certainly use
period.toStandardSeconds()
etc to decide on which format to use.