下面列出了怎么用java.text.DateFormatSymbols的API类实例代码及写法,或者点击链接到github查看源代码。
private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
String[] strings = null;
switch (field) {
case ERA:
strings = symbols.getEras();
break;
case MONTH:
strings = (style == LONG) ? symbols.getMonths() : symbols.getShortMonths();
break;
case DAY_OF_WEEK:
strings = (style == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
break;
case AM_PM:
strings = symbols.getAmPmStrings();
break;
}
return strings;
}
/**
* Initializes the locale specific month names.
*/
public void initNames() {
localInitialize = true;
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(locale);
String[] monthNames = dateFormatSymbols.getMonths();
if (comboBox.getItemCount() == 12) {
comboBox.removeAllItems();
}
for (int i = 0; i < 12; i++) {
comboBox.addItem(monthNames[i]);
}
localInitialize = false;
comboBox.setSelectedIndex(month);
}
public static void main(String[] args) {
List<Locale> avail = Arrays.asList(BreakIterator.getAvailableLocales());
diffLocale(BreakIterator.class, avail);
avail = Arrays.asList(Collator.getAvailableLocales());
diffLocale(Collator.class, avail);
avail = Arrays.asList(DateFormat.getAvailableLocales());
diffLocale(DateFormat.class, avail);
avail = Arrays.asList(DateFormatSymbols.getAvailableLocales());
diffLocale(DateFormatSymbols.class, avail);
avail = Arrays.asList(DecimalFormatSymbols.getAvailableLocales());
diffLocale(DecimalFormatSymbols.class, avail);
avail = Arrays.asList(NumberFormat.getAvailableLocales());
diffLocale(NumberFormat.class, avail);
avail = Arrays.asList(Locale.getAvailableLocales());
diffLocale(Locale.class, avail);
}
/**
* Creates a new formatter.
*
* @param zone the time zone used to extract the month and year from dates
* passed to this formatter (<code>null</code> not permitted).
* @param locale the locale used to determine the month names
* (<code>null</code> not permitted).
* @param chars the maximum number of characters to use from the month
* names, or zero to indicate that the entire month name
* should be used.
* @param showYear an array of flags that control whether or not the
* year is displayed for a particular month.
* @param yearFormatter the year formatter.
*/
public MonthDateFormat(TimeZone zone, Locale locale, int chars,
boolean[] showYear, DateFormat yearFormatter) {
ParamChecks.nullNotPermitted(locale, "locale");
DateFormatSymbols dfs = new DateFormatSymbols(locale);
String[] monthsFromLocale = dfs.getMonths();
this.months = new String[12];
for (int i = 0; i < 12; i++) {
if (chars > 0) {
this.months[i] = monthsFromLocale[i].substring(0,
Math.min(chars, monthsFromLocale[i].length()));
}
else {
this.months[i] = monthsFromLocale[i];
}
}
this.calendar = new GregorianCalendar(zone);
this.showYear = showYear;
this.yearFormatter = yearFormatter;
// the following is never used, but it seems that DateFormat requires
// it to be non-null. It isn't well covered in the spec, refer to
// bug parade 5061189 for more info.
this.numberFormat = NumberFormat.getNumberInstance();
}
public static Date str2dat( String arg0, String arg1, String val ) throws HopValueException {
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if ( arg1 != null ) {
dfs.setLocalPatternChars( arg1 );
}
if ( arg0 != null ) {
df.applyPattern( arg0 );
}
try {
return df.parse( val );
} catch ( Exception e ) {
throw new HopValueException( "TO_DATE Couldn't convert String to Date " + e.toString() );
}
}
public LDIFInputData() {
super();
nrInputFields = -1;
thisline = null;
nextline = null;
nf = NumberFormat.getInstance();
df = (DecimalFormat) nf;
dfs = new DecimalFormatSymbols();
daf = new SimpleDateFormat();
dafs = new DateFormatSymbols();
nr_repeats = 0;
filenr = 0;
fr = null;
zi = null;
is = null;
InputLDIF = null;
recordLDIF = null;
multiValueSeparator = ",";
totalpreviousfields = 0;
readrow = null;
indexOfFilenameField = -1;
}
/**
* Returns a panel of buttons, each button representing a day in the month. This is a sub-component of the DatePanel.
*
* @return the panel.
*/
private JPanel getCalendarPanel() {
final JPanel p = new JPanel( new GridLayout( 7, 7 ) );
final DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
final String[] weekDays = dateFormatSymbols.getShortWeekdays();
for ( int i = 0; i < this.WEEK_DAYS.length; i++ ) {
p.add( new JLabel( weekDays[ this.WEEK_DAYS[ i ] ], SwingConstants.CENTER ) );
}
this.buttons = new JButton[ 42 ];
for ( int i = 0; i < 42; i++ ) {
final JButton b = new JButton( "" );
b.setMargin( new Insets( 1, 1, 1, 1 ) );
b.setName( Integer.toString( i ) );
b.setFont( this.dateFont );
b.setFocusPainted( false );
b.putClientProperty( "JButton.buttonType", "square" ); //$NON-NLS-1$ $NON-NLS-2$
this.buttons[ i ] = b;
p.add( b );
}
return p;
}
private void setupWeekDaysPref() {
mPrefWeekDays = (MultiSelectListPreference) findPreference(PREF_KEY_QH_WEEKDAYS);
String[] days = new DateFormatSymbols(Locale.getDefault()).getWeekdays();
CharSequence[] entries = new CharSequence[7];
CharSequence[] entryValues = new CharSequence[7];
for (int i = 1; i <= 7; i++) {
entries[i - 1] = days[i];
entryValues[i - 1] = String.valueOf(i);
}
mPrefWeekDays.setEntries(entries);
mPrefWeekDays.setEntryValues(entryValues);
if (mPrefs.getStringSet(PREF_KEY_QH_WEEKDAYS, null) == null) {
Set<String> value = new HashSet<String>(Arrays.asList("2", "3", "4", "5", "6"));
mPrefs.edit().putStringSet(PREF_KEY_QH_WEEKDAYS, value).commit();
mPrefWeekDays.setValues(value);
}
}
private void parseText(Set<String> zids, Locale locale, TextStyle style, boolean ci) {
System.out.println("---------------------------------------");
DateTimeFormatter fmt = getFormatter(locale, style, ci);
for (String[] names : new DateFormatSymbols(locale).getZoneStrings()) {
if (!zids.contains(names[0])) {
continue;
}
String zid = names[0];
String expected = ZoneName.toZid(zid, locale);
parse(fmt, zid, expected, zid, locale, style, ci);
int i = style == TextStyle.FULL ? 1 : 2;
for (; i < names.length; i += 2) {
parse(fmt, zid, expected, names[i], locale, style, ci);
}
}
}
/**
* Constructs a new chooser with the specified month initially selected.
*
* @param month The month to initially select.
*/
public
MonthChooser(int month)
{
String[] months = new DateFormatSymbols().getMonths();
for(String monthName : months)
{
// There is a month with no displayable text that is not to be added.
if(monthName.length() != 0)
{
addItem(monthName);
}
}
setSelectedMonth(month);
setToolTipText(getProperty("MonthChooser.tip"));
}
private void parseText(Set<String> zids, Locale locale, TextStyle style, boolean ci) {
System.out.println("---------------------------------------");
DateTimeFormatter fmt = getFormatter(locale, style, ci);
for (String[] names : new DateFormatSymbols(locale).getZoneStrings()) {
if (!zids.contains(names[0])) {
continue;
}
String zid = names[0];
String expected = ZoneName.toZid(zid, locale);
parse(fmt, zid, expected, zid, locale, style, ci);
int i = style == TextStyle.FULL ? 1 : 2;
for (; i < names.length; i += 2) {
parse(fmt, zid, expected, names[i], locale, style, ci);
}
}
}
public static String[] getWeekDaysAbbreviation(int firstDayOfWeek) {
if (firstDayOfWeek < 1 || firstDayOfWeek > 7) {
throw new IllegalArgumentException("Day must be from Java Calendar class");
}
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(Locale.getDefault());
String[] shortWeekdays = dateFormatSymbols.getShortWeekdays();
String[] weekDaysFromSunday = new String[]{shortWeekdays[1], shortWeekdays[2],
shortWeekdays[3], shortWeekdays[4], shortWeekdays[5], shortWeekdays[6],
shortWeekdays[7]};
String[] weekDaysNames = new String[7];
for (int day = firstDayOfWeek - 1, i = 0; i < 7; i++, day++) {
day = day >= 7 ? 0 : day;
weekDaysNames[i] = weekDaysFromSunday[day].toUpperCase();
}
return weekDaysNames;
}
public static Date str2dat( String arg0, String arg1, String val ) throws KettleValueException {
SimpleDateFormat df = new SimpleDateFormat();
DateFormatSymbols dfs = new DateFormatSymbols();
if ( arg1 != null ) {
dfs.setLocalPatternChars( arg1 );
}
if ( arg0 != null ) {
df.applyPattern( arg0 );
}
try {
return df.parse( val );
} catch ( Exception e ) {
throw new KettleValueException( "TO_DATE Couldn't convert String to Date " + e.toString() );
}
}
@Test
public void builder() throws Exception {
final int year = 2001;
final int month = 6;
final Context appContext = InstrumentationRegistry.getTargetContext();
final String title = String.format(Locale.getDefault(),
"%s - %s",
new DateFormatSymbols().getMonths()[month].toUpperCase(),
year);
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
MonthYearPickerDialog dialog = new MonthYearPickerDialog(appContext,
year,
month,
null);
dialog.create();
assertEquals(title, dialog.getTitle());
assertEquals(dialog.getButton(AlertDialog.BUTTON_POSITIVE).getVisibility(), View.VISIBLE);
assertEquals(dialog.getButton(AlertDialog.BUTTON_NEGATIVE).getVisibility(), View.VISIBLE);
}
});
}
private void encodeMonthRow(ResponseWriter writer, Calendar date, Locale locale) throws IOException {
// writer.startElement("tr", this);
// writer.startElement("td", this);
writer.startElement("caption", this);
writer.writeAttribute("style", "font-weight: 600; background: #bbb", null);
writer.writeAttribute("class", "text-center", null);
// writer.writeAttribute("colspan", 6, null);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", locale);
DateFormatSymbols dfs = sdf.getDateFormatSymbols();
writer.write((dfs.getMonths())[date.get(Calendar.MONTH)]);
writer.endElement("caption");
// writer.endElement("td");
// writer.endElement("tr");
}
/**
* Sets the current locale.
*
* @param locale The current locale.
*/
@Override
protected void setCurrentLocale(Locale locale) {
super.setCurrentLocale(locale);
mTempDate = getCalendarForLocale(mTempDate, locale);
mMinDate = getCalendarForLocale(mMinDate, locale);
mMaxDate = getCalendarForLocale(mMaxDate, locale);
mCurrentDate = getCalendarForLocale(mCurrentDate, locale);
mNumberOfMonths = mTempDate.getActualMaximum(Calendar.MONTH) + 1;
mShortMonths = new DateFormatSymbols().getShortMonths();
if (usingNumericMonths()) {
// We're in a locale where a date should either be all-numeric, or all-text.
// All-text would require custom NumberPicker formatters for day and year.
mShortMonths = new String[mNumberOfMonths];
for (int i = 0; i < mNumberOfMonths; ++i) {
mShortMonths[i] = String.format("%d", i + 1);
}
}
}
private List<String> getAbbreviatedDayList() {
List<String> list = new ArrayList<String>();
ResourceLoader rl = new ResourceLoader();
DateFormatSymbols dfs = DateFormatSymbols.getInstance(rl.getLocale());
String[] daysOfWeek = dfs.getShortWeekdays();
if(meeting.isMonday())
list.add(daysOfWeek[Calendar.MONDAY]);
if(meeting.isTuesday())
list.add(daysOfWeek[Calendar.TUESDAY]);
if(meeting.isWednesday())
list.add(daysOfWeek[Calendar.WEDNESDAY]);
if(meeting.isThursday())
list.add(daysOfWeek[Calendar.THURSDAY]);
if(meeting.isFriday())
list.add(daysOfWeek[Calendar.FRIDAY]);
if(meeting.isSaturday())
list.add(daysOfWeek[Calendar.SATURDAY]);
if(meeting.isSunday())
list.add(daysOfWeek[Calendar.SUNDAY]);
return list;
}
public XMLInputSaxData() {
super();
thisline = null;
nextline = null;
nf = NumberFormat.getInstance();
df = (DecimalFormat) nf;
dfs = new DecimalFormatSymbols();
daf = new SimpleDateFormat();
dafs = new DateFormatSymbols();
nr_repeats = 0;
previousRow = null;
filenr = 0;
fr = null;
zi = null;
is = null;
}
private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
String[] strings = getFieldStrings(field, style, symbols);
if (strings != null) {
Map<String,Integer> names = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
if (strings[i].length() == 0) {
continue;
}
names.put(strings[i], i);
}
return names;
}
return null;
}
public static int getWeekdayIndex(String weekday) {
if (StringUtils.isBlank(weekday)) {
return -1;
} else {
weekday = weekday.toLowerCase().trim();
String[] localeWeekdays = DateFormatSymbols.getInstance().getWeekdays();
for (int i = 0; i < localeWeekdays.length; i++) {
if (localeWeekdays[i].toLowerCase().startsWith(weekday)) {
return i;
}
}
if (weekday.startsWith("so") || weekday.startsWith("su")) {
return Calendar.SUNDAY;
} else if (weekday.startsWith("mo")) {
return Calendar.MONDAY;
} else if (weekday.startsWith("di") || weekday.startsWith("tu")) {
return Calendar.TUESDAY;
} else if (weekday.startsWith("mi") || weekday.startsWith("we")) {
return Calendar.WEDNESDAY;
} else if (weekday.startsWith("do") || weekday.startsWith("th")) {
return Calendar.THURSDAY;
} else if (weekday.startsWith("fr")) {
return Calendar.FRIDAY;
} else if (weekday.startsWith("sa")) {
return Calendar.SATURDAY;
} else {
return -1;
}
}
}
/**
* Construct a Strategy that parses a TimeZone
*
* @param locale The Locale
*/
TimeZoneStrategy(final Locale locale) {
final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings();
for (String[] zone : zones) {
if (zone[ID].startsWith("GMT")) {
continue;
}
final TimeZone tz = TimeZone.getTimeZone(zone[ID]);
if (!tzNames.containsKey(zone[LONG_STD])) {
tzNames.put(zone[LONG_STD], tz);
}
if (!tzNames.containsKey(zone[SHORT_STD])) {
tzNames.put(zone[SHORT_STD], tz);
}
if (tz.useDaylightTime()) {
if (!tzNames.containsKey(zone[LONG_DST])) {
tzNames.put(zone[LONG_DST], tz);
}
if (!tzNames.containsKey(zone[SHORT_DST])) {
tzNames.put(zone[SHORT_DST], tz);
}
}
}
final StringBuilder sb = new StringBuilder();
sb.append("(GMT[+\\-]\\d{0,1}\\d{2}|[+\\-]\\d{2}:?\\d{2}|");
for (final String id : tzNames.keySet()) {
escapeRegex(sb, id, false).append('|');
}
sb.setCharAt(sb.length() - 1, ')');
validTimeZoneChars = sb.toString();
}
private String[] getFieldStrings(int field, int style, DateFormatSymbols symbols) {
int baseStyle = getBaseStyle(style); // ignore the standalone mask
// DateFormatSymbols doesn't support any narrow names.
if (baseStyle == NARROW_FORMAT) {
return null;
}
String[] strings = null;
switch (field) {
case ERA:
strings = symbols.getEras();
break;
case MONTH:
strings = (baseStyle == LONG) ? symbols.getMonths() : symbols.getShortMonths();
break;
case DAY_OF_WEEK:
strings = (baseStyle == LONG) ? symbols.getWeekdays() : symbols.getShortWeekdays();
break;
case AM_PM:
strings = symbols.getAmPmStrings();
break;
}
return strings;
}
public static String cfmlFormatTime(long timeMS, String cfmlFormatString, Locale loc) {
boolean replaceTimeMarker = false;
// Convert the CFML time format string to a Java format String
String javaFormatString = cfmlTimeToJavaFormatString(cfmlFormatString);
// If the mask contained only a single 't' (now an 'a') then we need
// to replace the time marker (AM or PM) with (A or P).
int pos = javaFormatString.indexOf('a');
if (pos != -1) {
if ((pos + 1 == javaFormatString.length()) || (javaFormatString.charAt(pos + 1) != 'a'))
replaceTimeMarker = true;
}
// Format the date
String javaValue = new SimpleDateFormat(javaFormatString, new DateFormatSymbols(loc)).format(new java.util.Date(timeMS));
// See if we need to replace the time marker (AM or PM) with (A or P).
if (replaceTimeMarker) {
pos = javaValue.indexOf("PM");
if (pos == -1)
pos = javaValue.indexOf("AM");
if (pos != -1) {
if (pos + 2 == javaValue.length())
javaValue = javaValue.substring(0, pos + 1);
else
javaValue = javaValue.substring(0, pos + 1) + javaValue.substring(pos + 2);
}
}
return javaValue;
}
public ConstantData() {
super();
nf = NumberFormat.getInstance();
df = (DecimalFormat) nf;
dfs = new DecimalFormatSymbols();
daf = new SimpleDateFormat();
dafs = new DateFormatSymbols();
}
/**
* Get the localised name of the day (ie Monday for en, Maandag for nl)
* @param day int according to Calendar.DAY_OF_WEEK
* @param locale locale to render dayname in
* @return
*/
public static String getDayName(int day, Locale locale) {
//localised daynames
String dayNames[] = new DateFormatSymbols(locale).getWeekdays();
String dayName = null;
try {
dayName = dayNames[day];
} catch (Exception e) {
log.error("Profile.getDayName() failed. " + e.getClass() + ": " + e.getMessage());
}
return dayName;
}
/**
* @param pattern {@link java.text.SimpleDateFormat} compatible pattern
* @param symbols optional date format symbols, overrides symbols for
* system locale
* @return the fast date format
*/
public static FastDateFormat getInstance
(String pattern, DateFormatSymbols symbols)
throws IllegalArgumentException
{
return getInstance(pattern, null, null, symbols);
}
/**
* Get the short and long values displayed for a field
* @param field The field of interest
* @return A sorted array of the field key / value pairs
*/
KeyValue[] getDisplayNames(int field) {
Integer fieldInt = Integer.valueOf(field);
KeyValue[] fieldKeyValues= nameValues.get(fieldInt);
if(fieldKeyValues==null) {
DateFormatSymbols symbols= DateFormatSymbols.getInstance(locale);
switch(field) {
case Calendar.ERA:
// DateFormatSymbols#getEras() only returns AD/BC or translations
// It does not work for the Thai Buddhist or Japanese Imperial calendars.
// see: https://issues.apache.org/jira/browse/TRINIDAD-2126
Calendar c = Calendar.getInstance(locale);
// N.B. Some calendars have different short and long symbols, e.g. ja_JP_JP
String[] shortEras = toArray(c.getDisplayNames(Calendar.ERA, Calendar.SHORT, locale));
String[] longEras = toArray(c.getDisplayNames(Calendar.ERA, Calendar.LONG, locale));
fieldKeyValues= createKeyValues(longEras, shortEras);
break;
case Calendar.DAY_OF_WEEK:
fieldKeyValues= createKeyValues(symbols.getWeekdays(), symbols.getShortWeekdays());
break;
case Calendar.AM_PM:
fieldKeyValues= createKeyValues(symbols.getAmPmStrings(), null);
break;
case Calendar.MONTH:
fieldKeyValues= createKeyValues(symbols.getMonths(), symbols.getShortMonths());
break;
default:
throw new IllegalArgumentException("Invalid field value "+field);
}
KeyValue[] prior = nameValues.putIfAbsent(fieldInt, fieldKeyValues);
if(prior!=null) {
fieldKeyValues= prior;
}
}
return fieldKeyValues;
}
public static int convertMonthToInt(char month[], DateFormatSymbols _dfs){
String months[] = _dfs.getMonths();
String shortmonths[] = _dfs.getShortMonths();
for(int i = 0; i < months.length; i++)
if(equal(month, months[i]) || equal(month, shortmonths[i]))
return i;
return -1;
}
private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
DateFormatSymbols symbols = DateFormatSymbols.getInstance(locale);
String[] strings = getFieldStrings(field, style, symbols);
if (strings != null) {
Map<String,Integer> names = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
if (strings[i].length() == 0) {
continue;
}
names.put(strings[i], i);
}
return names;
}
return null;
}
private
void
buildPanel()
{
String[] days = new DateFormatSymbols().getShortWeekdays();
int start = getCalendar().getFirstDayOfWeek();
// Build panel.
setFill(GridBagConstraints.BOTH);
addSpacer(0, 0, 1, 1, 1, 16);
// Weekdays.
for(int len = 0, col = 1; len < MAX_COLUMNS; ++len)
{
add(createWeekdayLabel(days[start++]), col++, 0, 1, 1, 14, 0);
if(start > MAX_COLUMNS)
{
start = SUNDAY; // Start the week over.
}
}
addSpacer(8, 0, 1, 1, 1, 0);
// Month days.
for(int len = 0, row = 1; row <= MAX_ROWS; ++row)
{
for(int col = 1; col <= MAX_COLUMNS; ++col, ++len)
{
add(getMonthDays()[len], col, row, 1, 1, 0, 14);
}
}
}