使用JodaTime自动将秒数转换为年/日/小时/分钟? [英] Convert seconds to years/days/hours/minutes automatically, using JodaTime?

查看:547
本文介绍了使用JodaTime自动将秒数转换为年/日/小时/分钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当说x超过3600秒时,有没有办法将'x'秒转换为y小时和z秒?同样,使用JodaTime时,当x超过60但小于3600秒时,将其转换为'a minutes and b seconds'?我明白我必须在PeriodFormatter中指定我需要的东西,但我不想指定它 - 我想要一个基于秒值的格式化文本。

Is there way to convert 'x' seconds to y hours and z seconds when say x exceeds 3600 seconds? Similarly, convert it to 'a minutes and b seconds' when x exceeds 60 but is less than 3600 seconds, using JodaTime? I understand that I would have to specify what I need in the PeriodFormatter, but I don't want to specify it - I want a formatted text based on value of seconds.

这类似于您在论坛上发布的内容,然后您的帖子最初将显示为10秒前发布... 1分钟后您会看到发布1分钟20秒前,同样数周,日,年。

This is similar to how you would post on a forum and then your post will initially be shown as 'posted 10 seconds ago'.. after 1 minute you would see 'posted 1minute 20 seconds ago' and likewise for weeks,days,years.

推荐答案

我不确定你为什么不想在 PeriodFormatter中指定你需要的东西 JodaTime 不知道您希望如何将字符串显示为字符串,因此您需要通过 PeriodFormatter 。

I'm not sure why you don't want to specify what you need in PeriodFormatter. JodaTime doesn't know how you want to display a period as a string, so you need to tell it via the PeriodFormatter.

由于3600秒是1小时,正确使用格式化程序会自动为您执行此操作。这是一个代码示例,它使用同一格式化程序上的许多不同输入来实现您想要的结果。

As 3600 seconds is 1 hour, using the formatter properly will automatically do this for you. Here's a code example using a number of different inputs on the same formatter which should achieve your desired result.

    Seconds s1 = Seconds.seconds(3601);
    Seconds s2 = Seconds.seconds(2000);
    Seconds s3 = Seconds.seconds(898298);
    Period p1 = new Period(s1);
    Period p2 = new Period(s2);
    Period p3 = new Period(s3);

    PeriodFormatter dhm = new PeriodFormatterBuilder()
        .appendDays()
        .appendSuffix(" day", " days")
        .appendSeparator(" and ")
        .appendHours()
        .appendSuffix(" hour", " hours")
        .appendSeparator(" and ")
        .appendMinutes()
        .appendSuffix(" minute", " minutes")
        .appendSeparator(" and ")
        .appendSeconds()
        .appendSuffix(" second", " seconds")
        .toFormatter();

    System.out.println(dhm.print(p1.normalizedStandard()));
    System.out.println(dhm.print(p2.normalizedStandard()));
    System.out.println(dhm.print(p3.normalizedStandard()));

产生输出::


1小时1秒

1 hour and 1 second

33分20秒

3天9小时和31分38秒

3 days and 9 hours and 31 minutes and 38 seconds

这篇关于使用JodaTime自动将秒数转换为年/日/小时/分钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆