Find Remaining day and time using jodatime

前端 未结 2 1732
说谎
说谎 2021-01-19 11:58

I want to compare(finding remaining days and time between two days) using joda time. I am taking two DateTime object like this(one is starting and another is ending)

相关标签:
2条回答
  • 2021-01-19 12:47

    Defines all standard fields from days downwards with PeriodType.dayTime().

    For example :

    DateTime startDate = DateTime.now(); // now() : since Joda Time 2.0
    DateTime endDate = new DateTime(2011, 12, 25, 0, 0);
    
    Period period = new Period(startDate, endDate, PeriodType.dayTime());
    
    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendDays().appendSuffix(" day ", " days ")
            .appendHours().appendSuffix(" hour ", " hours ")
            .appendMinutes().appendSuffix(" minute ", " minutes ")
            .appendSeconds().appendSuffix(" second ", " seconds ")
            .toFormatter();
    
    System.out.println(formatter.print(period));
    

    Sample output

    Period between startDate and endDate is

    47 days 12 hours 46 minutes 47 seconds


    Or

    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendPrefix("Day:", " Days:").appendDays()
            .appendPrefix(" Hour:", " Hours:").appendHours()
            .appendPrefix(" Minute:", " Minutes:").appendMinutes()
            .appendPrefix(" Second:", " Seconds:").appendSeconds()
            .toFormatter();
    

    with output

    Days:47 Hours:12 Minutes:46 Seconds:47

    0 讨论(0)
  • 2021-01-19 13:04

    If you want the output in prettier format then you can use this snippet too

    val startDate = DateTime.now()
    val endDate = DateTime(endTime)
    val period = Period(startDate, endDate)
    
    val periodFormatter = PeriodFormatterBuilder().apply {
        when {
            period.days > 0 -> appendDays().appendSuffix(" day", " days")
            period.hours > 0 -> appendHours().appendSuffix(" hour", " hours")
            period.minutes > 0 -> appendMinutes().appendSuffix(" minute", " minutes")
        }
    }.toFormatter()
    
    periodFormatter.print(period)
    
    0 讨论(0)
提交回复
热议问题