📄 simpledateformat.java
字号:
/* SimpleDateFormat.java -- A class for parsing/formating simple date constructs Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005 Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version. GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING. If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library. Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule. An independent module is a module which is not derived fromor based on this library. If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so. If you do not wish to do so, delete thisexception statement from your version. */package java.text;import gnu.java.text.AttributedFormatBuffer;import gnu.java.text.FormatBuffer;import gnu.java.text.FormatCharacterIterator;import gnu.java.text.StringFormatBuffer;import java.io.IOException;import java.io.InvalidObjectException;import java.io.ObjectInputStream;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Iterator;import java.util.Locale;import java.util.TimeZone;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * SimpleDateFormat provides convenient methods for parsing and formatting * dates using Gregorian calendars (see java.util.GregorianCalendar). */public class SimpleDateFormat extends DateFormat { /** * This class is used by <code>SimpleDateFormat</code> as a * compiled representation of a format string. The field * ID, size, and character used are stored for each sequence * of pattern characters. */ private class CompiledField { /** * The ID of the field within the local pattern characters. * Package private for use in out class. */ int field; /** * The size of the character sequence. * Package private for use in out class. */ int size; /** * The character used. */ private char character; /** * Constructs a compiled field using the * the given field ID, size and character * values. * * @param f the field ID. * @param s the size of the field. * @param c the character used. */ public CompiledField(int f, int s, char c) { field = f; size = s; character = c; } /** * Retrieves the ID of the field relative to * the local pattern characters. */ public int getField() { return field; } /** * Retrieves the size of the character sequence. */ public int getSize() { return size; } /** * Retrieves the character used in the sequence. */ public char getCharacter() { return character; } /** * Returns a <code>String</code> representation * of the compiled field, primarily for debugging * purposes. * * @return a <code>String</code> representation. */ public String toString() { StringBuffer builder; builder = new StringBuffer(getClass().getName()); builder.append("[field="); builder.append(field); builder.append(", size="); builder.append(size); builder.append(", character="); builder.append(character); builder.append("]"); return builder.toString(); } } /** * A list of <code>CompiledField</code>s, * representing the compiled version of the pattern. * * @see CompiledField * @serial Ignored. */ private transient ArrayList tokens; /** * The localised data used in formatting, * such as the day and month names in the local * language, and the localized pattern characters. * * @see DateFormatSymbols * @serial The localisation data. May not be null. */ private DateFormatSymbols formatData; /** * The date representing the start of the century * used for interpreting two digit years. For * example, 24/10/2004 would cause two digit * years to be interpreted as representing * the years between 2004 and 2104. * * @see #get2DigitYearStart() * @see #set2DigitYearStart(java.util.Date) * @see Date * @serial The start date of the century for parsing two digit years. * May not be null. */ private Date defaultCenturyStart; /** * The year at which interpretation of two * digit years starts. * * @see #get2DigitYearStart() * @see #set2DigitYearStart(java.util.Date) * @serial Ignored. */ private transient int defaultCentury; /** * The non-localized pattern string. This * only ever contains the pattern characters * stored in standardChars. Localized patterns * are translated to this form. * * @see #applyPattern(String) * @see #applyLocalizedPattern(String) * @see #toPattern() * @see #toLocalizedPattern() * @serial The non-localized pattern string. May not be null. */ private String pattern; /** * The version of serialized data used by this class. * Version 0 only includes the pattern and formatting * data. Version 1 adds the start date for interpreting * two digit years. * * @serial This specifies the version of the data being serialized. * Version 0 (or no version) specifies just <code>pattern</code> * and <code>formatData</code>. Version 1 adds * the <code>defaultCenturyStart</code>. This implementation * always writes out version 1 data. */ private int serialVersionOnStream = 1; // 0 indicates JDK1.1.3 or earlier /** * For compatability. */ private static final long serialVersionUID = 4774881970558875024L; // This string is specified in the root of the CLDR. We set it here // rather than doing a DateFormatSymbols(Locale.US).getLocalPatternChars() // since someone could theoretically change those values (though unlikely). private static final String standardChars = "GyMdkHmsSEDFwWahKzYeugAZ"; /** * Reads the serialized version of this object. * If the serialized data is only version 0, * then the date for the start of the century * for interpreting two digit years is computed. * The pattern is parsed and compiled following the process * of reading in the serialized data. * * @param stream the object stream to read the data from. * @throws IOException if an I/O error occurs. * @throws ClassNotFoundException if the class of the serialized data * could not be found. * @throws InvalidObjectException if the pattern is invalid. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); if (serialVersionOnStream < 1) { computeCenturyStart (); serialVersionOnStream = 1; } else // Ensure that defaultCentury gets set. set2DigitYearStart(defaultCenturyStart); // Set up items normally taken care of by the constructor. tokens = new ArrayList(); try { compileFormat(pattern); } catch (IllegalArgumentException e) { throw new InvalidObjectException("The stream pattern was invalid."); } } /** * Compiles the supplied non-localized pattern into a form * from which formatting and parsing can be performed. * This also detects errors in the pattern, which will * be raised on later use of the compiled data. * * @param pattern the non-localized pattern to compile. * @throws IllegalArgumentException if the pattern is invalid. */ private void compileFormat(String pattern) { // Any alphabetical characters are treated as pattern characters // unless enclosed in single quotes. char thisChar; int pos; int field; CompiledField current = null; for (int i = 0; i < pattern.length(); i++) { thisChar = pattern.charAt(i); field = standardChars.indexOf(thisChar); if (field == -1) { current = null; if ((thisChar >= 'A' && thisChar <= 'Z') || (thisChar >= 'a' && thisChar <= 'z')) { // Not a valid letter throw new IllegalArgumentException("Invalid letter " + thisChar + "encountered at character " + i + "."); } else if (thisChar == '\'') { // Quoted text section; skip to next single quote pos = pattern.indexOf('\'', i + 1); // First look for '' -- meaning a single quote. if (pos == i + 1) tokens.add("'"); else { // Look for the terminating quote. However, if we // see a '', that represents a literal quote and // we must iterate. StringBuffer buf = new StringBuffer(); int oldPos = i + 1; do { if (pos == -1) throw new IllegalArgumentException("Quotes starting at character " + i + " not closed."); buf.append(pattern.substring(oldPos, pos)); if (pos + 1 >= pattern.length() || pattern.charAt(pos + 1) != '\'') break; buf.append('\''); oldPos = pos + 2; pos = pattern.indexOf('\'', pos + 2); } while (true); tokens.add(buf.toString()); } i = pos; } else { // A special character tokens.add(new Character(thisChar)); } } else { // A valid field if ((current != null) && (field == current.field)) current.size++; else { current = new CompiledField(field, 1, thisChar); tokens.add(current); } } } } /** * Returns a string representation of this * class. * * @return a string representation of the <code>SimpleDateFormat</code> * instance. */ public String toString() { StringBuffer output = new StringBuffer(getClass().getName()); output.append("[tokens="); output.append(tokens); output.append(", formatData="); output.append(formatData); output.append(", defaultCenturyStart="); output.append(defaultCenturyStart); output.append(", defaultCentury="); output.append(defaultCentury); output.append(", pattern="); output.append(pattern); output.append(", serialVersionOnStream="); output.append(serialVersionOnStream); output.append(", standardChars="); output.append(standardChars); output.append("]"); return output.toString(); } /** * Constructs a SimpleDateFormat using the default pattern for * the default locale. */ public SimpleDateFormat() { /* * There does not appear to be a standard API for determining * what the default pattern for a locale is, so use package-scope * variables in DateFormatSymbols to encapsulate this. */ super(); Locale locale = Locale.getDefault(); calendar = new GregorianCalendar(locale); computeCenturyStart(); tokens = new ArrayList(); formatData = new DateFormatSymbols(locale); pattern = (formatData.dateFormats[DEFAULT] + ' ' + formatData.timeFormats[DEFAULT]); compileFormat(pattern); numberFormat = NumberFormat.getInstance(locale); numberFormat.setGroupingUsed (false); numberFormat.setParseIntegerOnly (true); numberFormat.setMaximumFractionDigits (0); } /** * Creates a date formatter using the specified non-localized pattern, * with the default DateFormatSymbols for the default locale. * * @param pattern the pattern to use. * @throws NullPointerException if the pattern is null. * @throws IllegalArgumentException if the pattern is invalid. */ public SimpleDateFormat(String pattern) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -