Close

Java Date Time - Duration.parse() Examples

Java Date Time Java Java API 


Class:

java.time.Duration

java.lang.Objectjava.lang.Objectjava.time.Durationjava.time.Durationjava.time.temporal.TemporalAmountTemporalAmountjava.lang.ComparableComparablejava.io.SerializableSerializableLogicBig

Method:

public static Duration parse(CharSequence text)

Obtains a Duration from a text string of pattern: PnDTnHnMn.nS, where
nD = number of days,
nH = number of hours,
nM = number of minutes,
n.nS = number of seconds, the decimal point may be either a dot or a comma.
T = must be used before the part consisting of nH, nM, n.nS

Examples


package com.logicbig.example.duration;

import java.time.Duration;

public class ParseExample {

public static void main(String... args) {
parse("PT20S");//T must be at the beginning to time part
parse("P2D");//2 day
parse("-P2D");//minus 2 days
parse("P-2DT-20S");//S for seconds
parse("PT20H");//H for hours
parse("PT220H");
parse("PT20M");//M for minutes
parse("PT20.3S");//second can be in fraction like 20.3
parse("P4DT12H20M20.3S");
parse("P-4DT-12H-20M-20.3S");
parse("-P4DT12H20M20.3S");
}

private static void parse(String pattern) {
Duration d = Duration.parse(pattern);
System.out.printf("Pattern: %s => %s%n", pattern, d);
}
}

Output

Pattern: PT20S => PT20S
Pattern: P2D => PT48H
Pattern: -P2D => PT-48H
Pattern: P-2DT-20S => PT-48H-20S
Pattern: PT20H => PT20H
Pattern: PT220H => PT220H
Pattern: PT20M => PT20M
Pattern: PT20.3S => PT20.3S
Pattern: P4DT12H20M20.3S => PT108H20M20.3S
Pattern: P-4DT-12H-20M-20.3S => PT-108H-20M-20.3S
Pattern: -P4DT12H20M20.3S => PT-108H-20M-20.3S




See Also