【问题标题】:JodaTime get values from periodJodaTime 从期间获取值
【发布时间】:2011-04-15 18:27:27
【问题描述】:

我有两个 DateTime,一个是'since'和'now'的时间

我需要的是在这之间获得时间。

我的问题是我想得到它的格式:

示例: 自 = '2010 年 4 月 17 日' 现在 = '2011 年 4 月 15 日'

我想要'0年11个月29天'

如果是“2010 年 4 月 13 日”,结果应该是: '1年0个月2天'

但是这个逻辑让我很困惑。

【问题讨论】:

    标签: java datetime date jodatime


    【解决方案1】:

    我不完全确定我是否听懂了你的问题。听起来像你想要的:

    DateTime since = ...;
    DateTime now = ...;
    
    Period period = new Period(since, now, PeriodType.yearMonthDay());
    int years = period.getYears();
    int months = period.getMonths();
    int days = period.getDays();
    

    如果不是这样,您能否提供更多详细信息?

    【讨论】:

    • 嗯.. 这解决了一些问题,只是另一个问题,它的月份是基于 0 的吗? 11 个月前的日期告诉我只有 10 个。
    • 不要考虑它,从那以后我输入了错误的月份。谢谢,它的作品。
    【解决方案2】:

    java.time

    以下引用来自home page of Joda-Time的通知:

    请注意,从 Java SE 8 开始,用户被要求迁移到 java.time (JSR-310) - JDK 的核心部分,它取代了这个项目。

    使用现代日期时间 API java.time 的解决方案:

    1. 使用Period#between 获取两个LocalDates 之间的时间段。
    2. 请注意,字符串中的月份名称是小写的,因此,您需要使用 parseCaseInsensitive 函数构建 DateTimeFormatter
    3. Never use DateTimeFormatter without a Locale

    演示:

    import java.time.LocalDate;
    import java.time.Period;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                    .parseCaseInsensitive()
                                    .appendPattern("d MMMM uuuu")
                                    .toFormatter(Locale.ENGLISH);
            
            LocalDate since = LocalDate.parse("17 april 2010", dtf);
            LocalDate now = LocalDate.parse("15 april 2011", dtf);
            
            Period period = Period.between(since, now);
            
            String strPeriod = String.format("%d years %d months %d days", period.getYears(), period.getMonths(),
                    period.getDays());
            System.out.println(strPeriod);
        }
    }
    

    输出:

    0 years 11 months 29 days
    

    ONLINE DEMO

    Trail: Date Time 了解有关现代日期时间 API 的更多信息。


    * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 2011-08-29
      • 2023-03-16
      • 1970-01-01
      • 2016-05-13
      • 2010-10-28
      • 1970-01-01
      相关资源
      最近更新 更多