Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright 2001-2005 Stephen Colebourne
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 package org.joda.time.format;
 
 import java.io.Writer;
 
Controls the printing and parsing of a time period to and from a string.

This class is the main API for printing and parsing used by most applications. Instances of this class are created via one of three factory classes:

An instance of this class holds a reference internally to one printer and one parser. It is possible that one of these may be null, in which case the formatter cannot print/parse. This can be checked via the isPrinter() and isParser() methods.

The underlying printer/parser can be altered to behave exactly as required by using a decorator modifier:

This returns a new formatter (instances of this class are immutable).

The main methods of the class are the printXxx and parseXxx methods. These are used as follows:

 // print using the default locale
 String periodStr = formatter.print(period);
 // print using the French locale
 String periodStr = formatter.withLocale(Locale.FRENCH).print(period);
 
 // parse using the French locale
 Period date = formatter.withLocale(Locale.FRENCH).parsePeriod(str);
 

Author(s):
Brian S O'Neill
Stephen Colebourne
Since:
1.0
 
 public class PeriodFormatter {

    
The internal printer used to output the datetime.
 
     private final PeriodPrinter iPrinter;
    
The internal parser used to output the datetime.
 
     private final PeriodParser iParser;
    
The locale to use for printing and parsing.
 
     private final Locale iLocale;
    
The period type used in parsing.
 
     private final PeriodType iParseType;

    
Creates a new formatter, however you will normally use the factory or the builder.

Parameters:
printer the internal printer, null if cannot print
parser the internal parser, null if cannot parse
 
     public PeriodFormatter(
             PeriodPrinter printerPeriodParser parser) {
         super();
          = printer;
          = parser;
          = null;
          = null;
     }

    
Constructor.

Parameters:
printer the internal printer, null if cannot print
parser the internal parser, null if cannot parse
locale the locale to use
type the parse period type
    private PeriodFormatter(
            PeriodPrinter printerPeriodParser parser,
            Locale localePeriodType type) {
        super();
         = printer;
         = parser;
         = locale;
         = type;
    }
    //-----------------------------------------------------------------------
    
Is this formatter capable of printing.

Returns:
true if this is a printer
    public boolean isPrinter() {
        return ( != null);
    }

    
Gets the internal printer object that performs the real printing work.

Returns:
the internal printer
    public PeriodPrinter getPrinter() {
        return ;
    }

    
Is this formatter capable of parsing.

Returns:
true if this is a parser
    public boolean isParser() {
        return ( != null);
    }

    
Gets the internal parser object that performs the real parsing work.

Returns:
the internal parser
    public PeriodParser getParser() {
        return ;
    }
    //-----------------------------------------------------------------------
    
Returns a new formatter with a different locale that will be used for printing and parsing.

A PeriodFormatter is immutable, so a new instance is returned, and the original is unaltered and still usable.

Parameters:
locale the locale to use
Returns:
the new formatter
    public PeriodFormatter withLocale(Locale locale) {
        if (locale == getLocale() || (locale != null && locale.equals(getLocale()))) {
            return this;
        }
        return new PeriodFormatter(locale);
    }

    
Gets the locale that will be used for printing and parsing.

Returns:
the locale to use
    public Locale getLocale() {
        return ;
    }
    //-----------------------------------------------------------------------
    
Returns a new formatter with a different PeriodType for parsing.

A PeriodFormatter is immutable, so a new instance is returned, and the original is unaltered and still usable.

Parameters:
type the type to use in parsing
Returns:
the new formatter
    public PeriodFormatter withParseType(PeriodType type) {
        if (type == ) {
            return this;
        }
        return new PeriodFormatter(type);
    }

    
Gets the PeriodType that will be used for parsing.

Returns:
the parse type to use
    public PeriodType getParseType() {
        return ;
    }
    //-----------------------------------------------------------------------
    
Prints a ReadablePeriod to a StringBuffer.

Parameters:
buf the formatted period is appended to this buffer
period the period to format, not null
    public void printTo(StringBuffer bufReadablePeriod period) {
        checkPrinter();
        checkPeriod(period);
        
        getPrinter().printTo(bufperiod);
    }

    
Prints a ReadablePeriod to a Writer.

Parameters:
out the formatted period is written out
period the period to format, not null
    public void printTo(Writer outReadablePeriod periodthrows IOException {
        checkPrinter();
        checkPeriod(period);
        
        getPrinter().printTo(outperiod);
    }

    
Prints a ReadablePeriod to a new String.

Parameters:
period the period to format, not null
Returns:
the printed result
    public String print(ReadablePeriod period) {
        checkPrinter();
        checkPeriod(period);
        
        PeriodPrinter printer = getPrinter();
        StringBuffer buf = new StringBuffer(printer.calculatePrintedLength(period));
        printer.printTo(bufperiod);
        return buf.toString();
    }

    
Checks whether printing is supported.

Throws:
java.lang.UnsupportedOperationException if printing is not supported
    private void checkPrinter() {
        if ( == null) {
            throw new UnsupportedOperationException("Printing not supported");
        }
    }

    
Checks whether the period is non-null.

Throws:
java.lang.IllegalArgumentException if the period is null
    private void checkPeriod(ReadablePeriod period) {
        if (period == null) {
            throw new IllegalArgumentException("Period must not be null");
        }
    }
    //-----------------------------------------------------------------------
    
Parses a period from the given text, at the given position, saving the result into the fields of the given ReadWritablePeriod. If the parse succeeds, the return value is the new text position. Note that the parse may succeed without fully reading the text.

The parse type of the formatter is not used by this method.

If it fails, the return value is negative, but the period may still be modified. To determine the position where the parse failed, apply the one's complement operator (~) on the return value.

Parameters:
period a period that will be modified
text text to parse
position position to start parsing from
Returns:
new position, if negative, parse failed. Apply complement operator (~) to get position of failure
Throws:
java.lang.IllegalArgumentException if any field is out of range
    public int parseInto(ReadWritablePeriod periodString textint position) {
        checkParser();
        checkPeriod(period);
        
        return getParser().parseInto(periodtextposition);
    }

    
Parses a period from the given text, returning a new Period.

Parameters:
text text to parse
Returns:
parsed value in a Period object
Throws:
java.lang.IllegalArgumentException if any field is out of range
    public Period parsePeriod(String text) {
        checkParser();
        
        return parseMutablePeriod(text).toPeriod();
    }

    
Parses a period from the given text, returning a new MutablePeriod.

Parameters:
text text to parse
Returns:
parsed value in a MutablePeriod object
Throws:
java.lang.IllegalArgumentException if any field is out of range
    public MutablePeriod parseMutablePeriod(String text) {
        checkParser();
        
        MutablePeriod period = new MutablePeriod(0, );
        int newPos = getParser().parseInto(periodtext, 0, );
        if (newPos >= 0) {
            if (newPos >= text.length()) {
                return period;
            }
        } else {
            newPos = ~newPos;
        }
        throw new IllegalArgumentException(FormatUtils.createErrorMessage(textnewPos));
    }

    
Checks whether parsing is supported.

Throws:
java.lang.UnsupportedOperationException if parsing is not supported
    private void checkParser() {
        if ( == null) {
            throw new UnsupportedOperationException("Parsing not supported");
        }
    }
New to GrepCode? Check out our FAQ X