Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert days, minutes, hours to seconds in Java Using Duration object failing

Quiz duration is specified as days, hours and minutes each in integers.

I am trying to convert combination of these to seconds. Below code I tried. but it always returns 0 seconds. I am using jdk 6

Integer hours = 3, days=4, minutes=20;
javax.xml.datatype.Duration duration = DatatypeFactory.newInstance().newDuration(true, 0, 0, 
                    days, 
                    hours, 
                    minutes, 
                    0);  
Integer seconds = duration.getSeconds(); // It always returns zero

Please guide.

like image 759
stack_user60 Avatar asked Dec 04 '25 17:12

stack_user60


2 Answers

As far as I can see your code you are trying to use

javax.xml.datatype.Duration

which will I believe only return the specified duration in the seconds. If you want to get the number of seconds in a time provided duration, you need to use

java.time.Duration

There is a parse method available that allows you to parse a CharSequence and get a proper instance of java.time.Duration which can be done as shown below

String toParse = "P"+days+"DT"+hours+"H"+minutes+"M";
Duration secondsDuration = Duration.parse(toParse);
System.out.println(secondsDuration.getSeconds());

This is a sample code you can read further documentation for the given method an different methods available for java.time.Duration.

like image 168
DevX Avatar answered Dec 07 '25 06:12

DevX


The JavaDocs for javax.xml.datatype.Duration.getSeconds() say

Obtains the value of the SECONDS field as an integer value, or 0 if not present. This method works just like getYears() except that this method works on the SECONDS field.

If you want to calculate the total amount of seconds this duration is representing, you will have to calculate them yourself, maybe like this (there may be better solutions):

private static int getInSeconds(javax.xml.datatype.Duration duration) {
    int totalSeconds = 0;
    totalSeconds += duration.getSeconds();
    totalSeconds += (duration.getMinutes() * 60);
    totalSeconds += (duration.getHours() * 60 * 60);
    totalSeconds += (duration.getDays() * 24 * 60 * 60);
    // ... calculate values for other fields here, too
    return totalSeconds;
}

For certain durations, an int will not be sufficient, keep that in mind, please.

Consider using java.time.Duration instead, if possible.

There is a backport of java.time for Java 6 and 7, but unfortunately, not for below.

like image 45
deHaar Avatar answered Dec 07 '25 07:12

deHaar