Java Date Time - Period parse(CharSequence text) example








Period parse(CharSequence text) creates a Period from a text string such as PnYnMnD.

For example, the following are valid inputs:

   "P2Y"             -- Period.ofYears(2)
   "P3M"             -- Period.ofMonths(3)
   "P4W"             -- Period.ofWeeks(4)
   "P5D"             -- Period.ofDays(5)
   "P2Y2M3D"         -- Period.of(2, 2, 3)
   "P2Y2M3W4D"       -- Period.of(2, 2, 25)
   "P-2Y2M"          -- Period.of(-2, 2, 0)
   "-P2Y2M"          -- Period.of(-2, -2, 0)




Syntax

parse has the following syntax.

public static Period parse(CharSequence text)

Example

The following example shows how to use parse.

import java.time.Period;
/*w w  w.ja  v a 2s . c o m*/
public class Main {
  public static void main(String[] args) {
    
    Period p = Period.parse("P5D");

    System.out.println(p.toString());

  }
}

The code above generates the following result.