1

I am getting a JSON response with value of time like this from Amazon:

"Duration": 
{
    "name": "Duration",
    "value": "PT7H"
} 

That stands for 7 hours. If the input is 5 minutes then it will be like this:

"Duration": 
{
    "name": "Duration",
    "value": "PT5M"
}

How can I convert the PT5M to time in seconds? So, if the string is "PT5M" (which is 300 seconds) then I want it to be 300 as the output.

Thanks!

T-Heron
  • 5,385
  • 7
  • 26
  • 52
JLT
  • 3,052
  • 9
  • 39
  • 86

4 Answers4

5

Those time durations are in standard ISO 8601 format. You can use the Java 8 date and time API. Use the Duration class' parse method. Then convert to other Chrono units. (Code deliberately not provided, so you can learn how to do this.)

Sualeh Fatehi
  • 4,700
  • 2
  • 24
  • 28
2

Java 8 Duration class

I think this is what you are looking for. Just use the parse method. It takes the same format that you are getting. And parsing of Json you can do with Jackson.

Avinash Anand
  • 655
  • 2
  • 15
  • 25
1

I can thik in a parsing function like this:

public static void main(String[] args)
 throws IOException, ParseException {

 String corvertme = "PT7H5M";

 Date extractedDate  = parseAmazonDate(corvertme);

 System.out.println(extractedDate);


 Calendar c = Calendar.getInstance();
 c.setTime(extractedDate);
 long daySeconds = (c.get(Calendar.SECOND) +
                    c.get(Calendar.MINUTE) * 60 +
                    c.get(Calendar.HOUR) * 3600);
 System.out.println(daySeconds);

 }

  private static Date parseAmazonDate(String corvertme) throws ParseException {

char[] hourCharacters = corvertme.replaceAll("[PT]", "").toCharArray();

 String[] hourArray =  "00:00:00".split(":");

 int HOUR_INDEX=0;
 int MIN_INDEX=1;
 int SEG_INDEX=2;

 char timeValue = 0;
 char posValue =  0;

 for(int i = 0; i < hourCharacters.length; i++){
     timeValue = hourCharacters[i];
     if(hourCharacters.length > i + 1){
         posValue = hourCharacters[++i];
     }

      switch (posValue) {
        case 'H':
                hourArray[HOUR_INDEX] = String.valueOf(timeValue);
                break;
        case 'M':
               hourArray[MIN_INDEX] = String.valueOf(timeValue);
                break;
        case 'S':
                hourArray[SEG_INDEX] = String.valueOf(timeValue);
        default:
            break;
        }   

 }


 String stringDate = hourArray[HOUR_INDEX] + ":"+hourArray[MIN_INDEX] + ":" + hourArray[SEG_INDEX];

 return new SimpleDateFormat("HH:mm:ss").parse(stringDate);

}

Hope Help you!

Matías W.
  • 350
  • 2
  • 17
-1

This question is similar to Parse ISO Date.

Just find out the last index of M, H and S. Find the values of minute. hour and second by parsing the string to int. And then calculate time.

Community
  • 1
  • 1
Prabir Ghosh
  • 430
  • 3
  • 7