1

I'm trying to format my String in a certain format. Below is the full code:

package com.my.app.aml.util;

import org.apache.commons.lang3.time.DurationFormatUtils;

import java.time.Duration;
import java.time.LocalDateTime;

import static com.my.app.aml.util.DateTimeUtil.currentTime;
import static java.time.Duration.between;
import static org.apache.commons.lang3.time.DurationFormatUtils.formatDuration;
import static org.joda.time.DateTimeConstants.*;

public class TestDuration {

    private static String slaAsStringNew(LocalDateTime tillDate) {
        if (tillDate == null) {
            return null;
        }
        if (tillDate.isBefore(currentTime())) {
            Duration duration = between(tillDate, currentTime());
            return "-" + formatDuration(duration.toMillis(), "d:H:m", true);
        } else {
            Duration duration = between(currentTime(), tillDate);
            return formatDuration(duration.toMillis(), "d:H:m", true);
        }
    }

    public static void main(String[] args) {
        System.out.println(slaAsStringNew(LocalDateTime.now().minusDays(4).plusHours(1).plusMinutes(30)));
    }
}

The output is -3:22:30 however I want to format it as: -3d 22h 30m. The obvious splitting and stitching approach just felt a bit of a mess so looking for other elegant solutions.

saran3h
  • 12,353
  • 4
  • 42
  • 54
  • 1
    Are you using Java9 or higher? – Eritrean May 05 '21 at 11:50
  • For Java 8, there are no available styles you can create using [DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) similar to yours. You will have to create one using [DateTimeFormatterBuilder](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html) – Kitswas May 05 '21 at 12:03
  • `yourString.replaceAll("(-?\\d+):(\\d+):(\\d+)", "$1d $2h $3m");` – DevilsHnd - 退職した May 05 '21 at 12:17

1 Answers1

1

I would do it like this:

return "-" + formatDuration(duration.toMillis(), "d'd' Hh m'm'", true);

It works and gives output as you want, but I'm not sure it's fully correct, because I'm not familiar with this library.

Another approach that could work, if you use 'org.joda.time' library:

PeriodFormatter formatter = new PeriodFormatterBuilder()
   .appendDays()
   .appendSuffix("d")
   .appendSeparator(" ")
   .appendHours()
   .appendSuffix("h")
   .appendSeparator(" ")
   .appendMinutes()
   .appendSuffix("m")
   .toFormatter();

org.joda.time.Duration jodaDuration = new org.joda.time.Duration(duration.toMillis());
String formattedDuration = "-" + formatter.print(jodaDuration.toPeriod().normalizedStandard());
Matt
  • 1,298
  • 1
  • 12
  • 31
  • I figured out by getting a cue from SimpleDateFormat package. The first example works just fine. – saran3h May 05 '21 at 12:36