Java Code Examples for java.text.DateFormatSymbols

The following are top voted examples for showing how to use java.text.DateFormatSymbols. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: MainCalendar   File: WeekAdapter.java   View source code 7 votes vote down vote up
public WeekAdapter(Context context){
    this.context = context;

    this.list = new ArrayList<>();
    String[] weekdays = new DateFormatSymbols().getWeekdays();
    this.list.add(weekdays[Calendar.SUNDAY]);
    this.list.add(weekdays[Calendar.MONDAY]);
    this.list.add(weekdays[Calendar.TUESDAY]);
    this.list.add(weekdays[Calendar.WEDNESDAY]);
    this.list.add(weekdays[Calendar.THURSDAY]);
    this.list.add(weekdays[Calendar.FRIDAY]);
    this.list.add(weekdays[Calendar.SATURDAY]);

    for(int i = 0; i < list.size(); i++) {
        setIsSelected(i, false);
    }
}
 
Example 2
Project: airgram   File: FastDateParser.java   View source code 6 votes vote down vote up
private static String[] getDisplayNameArray(int field, boolean isLong, Locale locale) {
    DateFormatSymbols dfs = new DateFormatSymbols(locale);
    switch (field) {
        case Calendar.AM_PM:
            return dfs.getAmPmStrings();
        case Calendar.DAY_OF_WEEK:
            return isLong ? dfs.getWeekdays() : dfs.getShortWeekdays();
        case Calendar.ERA:
            return dfs.getEras();
        case Calendar.MONTH:
            return isLong ? dfs.getMonths() : dfs.getShortMonths();
    }
    return null;
}
 
Example 3
Project: myfaces-trinidad   File: DateRestrictionValidator.java   View source code 6 votes vote down vote up
/**
 * Builds an error message indicating invalid week-day selection
 * @param context FacesContext
 * @param component inputDate instance
 * @param converter date converter instance
 * @param value user submitted value
 * @param dayOfTheWeekIndex Week day index as returned by Calendar.DAY_OF_WEEK on the value
 * @return FacesMessage
 */
private FacesMessage _getWrongWeekDayMessage(
  FacesContext  context,
  UIComponent   component,
  Converter     converter,
  Object        value,
  int           dayOfTheWeekIndex)
{ 
  RequestContext reqContext = RequestContext.getCurrentInstance();      
  Locale locale = reqContext.getFormattingLocale();

  if (locale == null)
  {
    locale = context.getViewRoot().getLocale();
  }
    
  Object cValue = _getConvertedValue(context, component, converter, value);
  Object msg   = _getRawInvalidDaysOfWeekMessageDetail();
  Object label = ValidatorUtils.getComponentLabel(component);
  String[] weekdays = new DateFormatSymbols(locale).getWeekdays();

  // Fetch the localized week name 
  Object[] params = {label, cValue, weekdays[dayOfTheWeekIndex]};

  return MessageFactory.getMessage(context, WEEKDAY_MESSAGE_ID, msg, params, component);
}
 
Example 4
Project: NumberPadTimePicker   File: ButtonTextModel.java   View source code 6 votes vote down vote up
ButtonTextModel(@NonNull LocaleModel localeModel, boolean is24HourMode) {
    final String timeSeparator = localeModel.getTimeSeparator(is24HourMode);
    String leftAltText, rightAltText;
    if (is24HourMode) {
        leftAltText = String.format("%02d", 0);
        rightAltText = String.format("%02d", 30);
        leftAltText = localeModel.isLayoutRtl() ?
                (leftAltText + timeSeparator) : (timeSeparator + leftAltText);
        rightAltText = localeModel.isLayoutRtl() ?
                (rightAltText + timeSeparator) : (timeSeparator + rightAltText);
    } else {
        String[] amPm = new DateFormatSymbols().getAmPmStrings();
        // TODO: Get localized. Or get the same am/pm strings as the framework.
        leftAltText = amPm[0].length() > 2 ? "AM" : amPm[0];
        rightAltText = amPm[1].length() > 2 ? "PM" : amPm[1];
    }
    mAltButtonsTexts[0] = leftAltText;
    mAltButtonsTexts[1] = rightAltText;
    mIs24HourMode = is24HourMode;
}
 
Example 5
Project: PlusGram   File: FastDateParser.java   View source code 6 votes vote down vote up
private static String[] getDisplayNameArray(int field, boolean isLong, Locale locale) {
    DateFormatSymbols dfs = new DateFormatSymbols(locale);
    switch (field) {
        case Calendar.AM_PM:
            return dfs.getAmPmStrings();
        case Calendar.DAY_OF_WEEK:
            return isLong ? dfs.getWeekdays() : dfs.getShortWeekdays();
        case Calendar.ERA:
            return dfs.getEras();
        case Calendar.MONTH:
            return isLong ? dfs.getMonths() : dfs.getShortMonths();
    }
    return null;
}
 
Example 6
Project: GravityBox   File: QuietHoursActivity.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 7
Project: jdk8u-jdk   File: TestZoneTextPrinterParser.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 8
Project: openjdk-jdk10   File: TestZoneTextPrinterParser.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 9
Project: openjdk-jdk10   File: Bug8149452.java   View source code 6 votes vote down vote up
public static void main(String[] args) {

        List<String> listNotFound = new ArrayList<>();
        String[][] zoneStrings = DateFormatSymbols.getInstance()
                .getZoneStrings();
        for (String tzID : TimeZone.getAvailableIDs()) {
            if (!Arrays.stream(zoneStrings)
                    .anyMatch(zone -> tzID.equalsIgnoreCase(zone[0]))) {
                // to ignore names for Etc/GMT[+-][0-9]+ which are not supported
                // Also ignore the TimeZone DisplayNames with GMT[+-]:hh:mm
                if (!tzID.startsWith("Etc/GMT")
                        && !tzID.startsWith("GMT")
                        && !TimeZone.getTimeZone(tzID).getDisplayName().startsWith("GMT")) {
                    listNotFound.add(tzID);
                }
            }
        }

        if (!listNotFound.isEmpty()) {
            throw new RuntimeException("Test Failed: Time Zone Strings for "
                    + listNotFound + " not found");
        }

    }
 
Example 10
Project: openjdk-jdk10   File: Bug8167273.java   View source code 6 votes vote down vote up
/**
 * tests that era names retrieved from Calendar.getDisplayNames map should
 * match with that of Era names retrieved from DateFormatSymbols.getEras()
 * method for all Gregorian Calendar locales .
 */
public static void testEraName() {
    Set<Locale> allLocales = Set.of(Locale.getAvailableLocales());
    Set<Locale> JpThlocales = Set.of(
            new Locale("th", "TH"),
            new Locale("ja", "JP", "JP"), new Locale("th", "TH", "TH")
    );
    Set<Locale> allLocs = new HashSet<>(allLocales);
    // Removing Japense and Thai Locales to check  Gregorian Calendar Locales
    allLocs.removeAll(JpThlocales);
    allLocs.forEach((locale) -> {
        Calendar cal = Calendar.getInstance(locale);
        Map<String, Integer> names = cal.getDisplayNames(Calendar.ERA, Calendar.ALL_STYLES, locale);
        DateFormatSymbols symbols = new DateFormatSymbols(locale);
        String[] eras = symbols.getEras();
        for (String era : eras) {
            if (!names.containsKey(era)) {
                reportMismatch(names.keySet(), eras, locale);
            }
        }
    });
}
 
Example 11
Project: openjdk-jdk10   File: Bug8167273.java   View source code 6 votes vote down vote up
/**
 * tests that Eras names returned from DateFormatSymbols.getEras()
 * and Calendar.getDisplayNames() should not be empty for any Locale.
 */
private static void testEmptyEraNames() {
    Set<Locale> allLocales = Set.of(Locale.getAvailableLocales());
    allLocales.forEach((loc) -> {
        DateFormatSymbols dfs = new DateFormatSymbols(loc);
        Calendar cal = Calendar.getInstance(loc);
        Map<String, Integer> names = cal.getDisplayNames(Calendar.ERA, Calendar.ALL_STYLES, loc);
        Set<String> CalendarEraNames = names.keySet();
        String[] eras = dfs.getEras();
        for (String era : eras) {
            if (era.isEmpty()) {
                throw new RuntimeException("Empty era names retrieved for DateFomatSymbols.getEras"
                        + " for locale " + loc);
            }
        }
        CalendarEraNames.stream().filter((erakey) -> (erakey.isEmpty())).forEachOrdered((l) -> {
            throw new RuntimeException("Empty era names retrieved for Calendar.getDisplayName"
                    + " for locale " + loc);
        });
    });

}
 
Example 12
Project: openjdk-jdk10   File: Bug8001562.java   View source code 6 votes vote down vote up
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);
}
 
Example 13
Project: black-mirror   File: TimeWidgetView.java   View source code 6 votes vote down vote up
/**
 * Metoda pokazująca widżet dla podanej strefy czasowej.
 *
 * @param timezone strefa czasowa.
 */
public void show(String timezone) {
    clock.setTimeZone(timezone);
    clock.setFormat24Hour(clock.getFormat24Hour());
    clock.setFormat12Hour(null);
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone));
    String[] dayNames = new DateFormatSymbols(new Locale("pl")).getWeekdays();
    String[] monthNames = new DateFormatSymbols(new Locale("pl")).getMonths();
    date.setText(String.format(context.getString(R.string.date_format), dayNames[calendar.get(Calendar.DAY_OF_WEEK)],
            Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)),
            monthNames[calendar.get(Calendar.MONTH)]));
    YoYo.with(Techniques.ZoomIn)
            .onStart(new YoYo.AnimatorCallback() {
                @Override
                public void call(Animator animator) {
                    setVisibility(VISIBLE);
                }
            })
            .playOn(this);
}
 
Example 14
Project: EsperantoRadio   File: RepeatPreference.java   View source code 6 votes vote down vote up
public RepeatPreference(Context context, AttributeSet attrs) {
  super(context, attrs);

  String[] weekdays = new DateFormatSymbols().getWeekdays();
  String[] values = new String[]{
      weekdays[Calendar.MONDAY],
      weekdays[Calendar.TUESDAY],
      weekdays[Calendar.WEDNESDAY],
      weekdays[Calendar.THURSDAY],
      weekdays[Calendar.FRIDAY],
      weekdays[Calendar.SATURDAY],
      weekdays[Calendar.SUNDAY],};
  setEntries(values);
  setEntryValues(values);
}
 
Example 15
Project: DateTimePicker   File: TimePicker.java   View source code 6 votes vote down vote up
static String[] getAmPmStrings(Context context) {
    final Locale locale = context.getResources().getConfiguration().locale;
    /*final LocaleData d = LocaleData.get(locale);

    final String[] result = new String[2];
    result[0] = d.amPm[0].length() > 4 ? d.narrowAm : d.amPm[0];
    result[1] = d.amPm[1].length() > 4 ? d.narrowPm : d.amPm[1];
    return result;*/

    final String[] result = new String[2];
    final String[] amPm;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        amPm = android.icu.text.DateFormatSymbols.getInstance(locale).getAmPmStrings();
    } else {
        amPm = DateFormatSymbols.getInstance(locale).getAmPmStrings();
    }

    result[0] = amPm[0].length() > 4 ? amPm[0].substring(0, 1) : amPm[0];
    result[1] = amPm[1].length() > 4 ? amPm[1].substring(0, 1) : amPm[1];

    return result;
}
 
Example 16
Project: DateTimePicker   File: DatePickerSpinnerDelegate.java   View source code 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 17
Project: openjdk9   File: TestZoneTextPrinterParser.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 18
Project: min-cal-widget   File: WeekDayHeaderUtil.java   View source code 6 votes vote down vote up
public static void setCellHeaderWeekDays(final RemoteViews headerRowRv, final int firstDayOfWeek, final Context context) {

        DateFormatSymbols dfs = DateFormatSymbols.getInstance();
        String[] weekdays = dfs.getShortWeekdays();

        ThemesUtil.Theme theme = ConfigurationUtil.getTheme(context);

        for (int i = 0; i < Calendar.DAY_OF_WEEK; i++) {

            RemoteViews rv;
            int current = (firstDayOfWeek + i) % Calendar.DAY_OF_WEEK == 0 ? firstDayOfWeek + i : (firstDayOfWeek + i) % Calendar.DAY_OF_WEEK;
            if (current == Calendar.SATURDAY) {
                rv = setSpecificWeekDay(context, weekdays[current], theme.getCellHeaderSaturday());
            } else if (current == Calendar.SUNDAY) {
                rv = setSpecificWeekDay(context, weekdays[current], theme.getCellHeaderSunday());
            } else {
                rv = setSpecificWeekDay(context, weekdays[current], theme.getCellHeader());
            }
            headerRowRv.addView(R.id.row_container, rv);
        }
    }
 
Example 19
Project: openjdk9   File: Bug8149452.java   View source code 6 votes vote down vote up
public static void main(String[] args) {

        List<String> listNotFound = new ArrayList<>();
        String[][] zoneStrings = DateFormatSymbols.getInstance()
                .getZoneStrings();
        for (String tzID : TimeZone.getAvailableIDs()) {
            if (!Arrays.stream(zoneStrings)
                    .anyMatch(zone -> tzID.equalsIgnoreCase(zone[0]))) {
                // to ignore names for Etc/GMT[+-][0-9]+ which are not supported
                if (!tzID.startsWith("Etc/GMT") && !tzID.startsWith("GMT")) {
                    listNotFound.add(tzID);
                }
            }
        }

        if (!listNotFound.isEmpty()) {
            throw new RuntimeException("Test Failed: Time Zone Strings for "
                    + listNotFound + " not found");
        }

    }
 
Example 20
Project: ccu-historian   File: MonthDateFormat.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 21
Project: jfreechart   File: MonthDateFormat.java   View source code 6 votes vote down vote up
/**
 * Creates a new formatter.
 *
 * @param zone  the time zone used to extract the month and year from dates
 *              passed to this formatter ({@code null} not permitted).
 * @param locale  the locale used to determine the month names
 *                ({@code null} 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) {
    Args.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();
}
 
Example 22
Project: LiteSDK   File: DateUtils.java   View source code 6 votes vote down vote up
public static boolean isExpired(String issued, long validate) {
    if (TextUtils.isEmpty(issued)) {
        return true;
    }
    String template = "EEE, d MMM yyyy HH:mm:ss Z";
    SimpleDateFormat dateFormat = getSdf();
    dateFormat.applyPattern(template);
    dateFormat.setDateFormatSymbols(new DateFormatSymbols(Locale.US));
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    try {
        Date d = dateFormat.parse(issued);
        long current = System.currentTimeMillis();
        return current - d.getTime() > validate * 1000;

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return true;
}
 
Example 23
Project: MaterialDateTimePicker   File: MonthPickerView.java   View source code 6 votes vote down vote up
public void init() {
    String[] months = new DateFormatSymbols().getMonths();
    ArrayList<String> monthsList = new ArrayList<>();
    int awalBulan,akhirBulan;
    if(mController.getMinYear()>=mController.getCurrentYear()){
        awalBulan=mController.getMinMonth();
    }else{
        awalBulan=0;
    }
    if(mController.getMaxYear()<=mController.getCurrentYear()){
        akhirBulan=mController.getMaxMonth();
    }else{
        akhirBulan=11;
    }
    
    for (int month = awalBulan; month <= akhirBulan; month++) {
        monthsList .add(months[month]);
    }
    mAdapter = new MonthAdapter(ctx, R.layout.mdtp_year_label_text_view, monthsList);
    setAdapter(mAdapter);
}
 
Example 24
Project: aya-lang   File: MonthDateFormat.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 25
Project: NonDex   File: DateFormatSymbolsTest.java   View source code 6 votes vote down vote up
@Test
public void getZoneStringsTest() {

    DateFormatSymbols dfs = new DateFormatSymbols();
    String[][] result = dfs.getZoneStrings();
    for (int i = 0; i < 10; i++) {
        if (!Arrays.deepEquals(result, dfs.getZoneStrings())) {
            return;
        }
    }
    fail("getZoneStrings did not extend in 10 tries; something is likely fishy.");
}
 
Example 26
Project: TbRepeatPicker   File: RecurrenceOptionsCreator.java   View source code 6 votes vote down vote up
private static String makeWeekTipInfo(Context context, RecurrenceModel mModel) {
    String str = "";
    String[] dayOfWeekString = new DateFormatSymbols().getWeekdays();
    int idx = DateUtil.getFirstDayOfWeek();
    for (int i = 0; i < mModel.weeklyByDayOfWeek.length; i++) {
        if (mModel.weeklyByDayOfWeek[i]) {
            if (TextUtils.isEmpty(str)) {
                str = dayOfWeekString[RRuleContants.TIME_DAY_TO_CALENDAR_DAY[idx]];
            } else {
                str = str + ", " + dayOfWeekString[RRuleContants.TIME_DAY_TO_CALENDAR_DAY[idx]];
            }
        }
        if (++idx >= 7) {
            idx = 0;
        }
    }

    str = str.replaceAll(", (?=[^, ]*$)", context.getResources().getString(R.string.recurrence_interval_and));

    return str;
}
 
Example 27
Project: jdk8u_jdk   File: TestZoneTextPrinterParser.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 28
Project: lookaside_java-1.8.0-openjdk   File: TestZoneTextPrinterParser.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 29
Project: BottomSheetPickers   File: ButtonTextModel.java   View source code 6 votes vote down vote up
ButtonTextModel(@NonNull LocaleModel localeModel, boolean is24HourMode) {
    final String timeSeparator = localeModel.getTimeSeparator(is24HourMode);
    String leftAltText, rightAltText;
    if (is24HourMode) {
        leftAltText = String.format("%02d", 0);
        rightAltText = String.format("%02d", 30);
        leftAltText = localeModel.isLayoutRtl() ?
                (leftAltText + timeSeparator) : (timeSeparator + leftAltText);
        rightAltText = localeModel.isLayoutRtl() ?
                (rightAltText + timeSeparator) : (timeSeparator + rightAltText);
    } else {
        String[] amPm = new DateFormatSymbols().getAmPmStrings();
        // TODO: Get localized. Or get the same am/pm strings as the framework.
        leftAltText = amPm[0].length() > 2 ? "AM" : amPm[0];
        rightAltText = amPm[1].length() > 2 ? "PM" : amPm[1];
    }
    mAltButtonsTexts[0] = leftAltText;
    mAltButtonsTexts[1] = rightAltText;
    mIs24HourMode = is24HourMode;
}
 
Example 30
Project: ticdesign   File: DatePicker.java   View source code 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 31
Project: LGoodDatePicker   File: ExtraDateStrings.java   View source code 6 votes vote down vote up
/**
 * getStandaloneMonthName, This returns a "standalone version" month name for the specified
 * month, in the specified locale. In some languages, including Russian and Czech, the
 * standalone version of the month name is different from the version of the month name you
 * would use as part of a full date. (Is different from the formatting version).
 *
 * This tries to get the standalone version first. If no mapping is found for a standalone
 * version (Presumably because the supplied language has no standalone version), then this will
 * return the formatting version of the month name.
 */
private static String getStandaloneMonthName(Month month, Locale locale, boolean capitalize,
        boolean shortVersion) {
    // Attempt to get the standalone version of the month name.
    TextStyle style = (shortVersion) ? TextStyle.SHORT_STANDALONE : TextStyle.FULL_STANDALONE;
    String monthName = month.getDisplayName(style, locale);
    String monthNumber = "" + month.getValue();
    // If no mapping was found, then get the "formatting version" of the month name.
    if (monthName.equals(monthNumber)) {
        DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
        if (shortVersion) {
            monthName = dateSymbols.getShortMonths()[month.getValue() - 1];
        } else {
            monthName = dateSymbols.getMonths()[month.getValue() - 1];
        }
    }
    // If needed, capitalize the month name.
    if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
        monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
    }
    return monthName;
}
 
Example 32
Project: LGoodDatePicker   File: ExtraDateStrings.java   View source code 6 votes vote down vote up
/**
 * getFormattingMonthName, This returns a "formatting version" month name for the specified
 * month, in the specified locale. In some languages, including Russian and Czech, the
 * standalone version of the month name is different from the version of the month name you
 * would use as part of a full date. (Is different from the formatting version).
 */
private static String getFormattingMonthName(Month month, Locale locale, boolean capitalize,
        boolean shortVersion) {
    // Get the "formatting version" of the month name.
    DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
    String monthName;
    if (shortVersion) {
        monthName = dateSymbols.getShortMonths()[month.getValue() - 1];
    } else {
        monthName = dateSymbols.getMonths()[month.getValue() - 1];
    }
    // If needed, capitalize the month name.
    if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
        monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
    }
    return monthName;
}
 
Example 33
Project: code-similarity   File: AnnualSalesCalc.java   View source code 6 votes vote down vote up
private static void printMatrix() {
    System.out.print("\t\t");
    String[] monthDisplayNames =
            (new DateFormatSymbols()).getShortMonths();
    for (String strName : monthDisplayNames) {
        System.out.printf("%8s", strName);
    }
    System.out.printf("%n%n");
    for (int i = 0; i < NUMBER_OF_CUSTOMERS; i++) {
        System.out.printf("Client ID: 1%02d", i);
        for (int j = 0; j < NUMBER_OF_MONTHS; j++) {
            System.out.printf("%8d", salesMatrix[i][j]);
        }
        System.out.println();
    }
    System.out.printf("%n%n");
}
 
Example 34
Project: jtransc   File: Calendar.java   View source code 6 votes vote down vote up
private String[] getDisplayNameArray(int field, int style, Locale locale) {
	if (field < 0 || field >= FIELD_COUNT) {
		throw new IllegalArgumentException("bad field " + field);
	}
	checkStyle(style);
	DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale);
	switch (field) {
		case AM_PM:
			return dfs.getAmPmStrings();
		case DAY_OF_WEEK:
			return (style == LONG) ? dfs.getWeekdays() : dfs.getShortWeekdays();
		case ERA:
			return dfs.getEras();
		case MONTH:
			return (style == LONG) ? dfs.getMonths() : dfs.getShortMonths();
	}
	return null;
}
 
Example 35
Project: NotifyTools   File: DateLocaleConverter.java   View source code 5 votes vote down vote up
/**
  * Convert a pattern from a localized format to the default format.
  *
  * @param locale   The locale
  * @param localizedPattern The pattern in 'local' symbol format
  * @return pattern in 'default' symbol format
  */
 private String convertLocalizedPattern(final String localizedPattern, final Locale locale) {

     if (localizedPattern == null) {
        return null;
     }

     // Note that this is a little obtuse.
     // However, it is the best way that anyone can come up with
     // that works with some 1.4 series JVM.

     // Get the symbols for the localized pattern
     final DateFormatSymbols localizedSymbols = new DateFormatSymbols(locale);
     final String localChars = localizedSymbols.getLocalPatternChars();

     if (DEFAULT_PATTERN_CHARS.equals(localChars)) {
         return localizedPattern;
     }

     // Convert the localized pattern to default
     String convertedPattern = null;
     try {
         convertedPattern = convertPattern(localizedPattern,
                                            localChars,
                                            DEFAULT_PATTERN_CHARS);
     } catch (final Exception ex) {
         log.debug("Converting pattern '" + localizedPattern + "' for " + locale, ex);
     }
     return convertedPattern;
}
 
Example 36
Project: TimePicker   File: AmPmCirclesView.java   View source code 5 votes vote down vote up
public void initialize(Context context, int amOrPm) {
    if (mIsInitialized) {
        Log.e(TAG, "AmPmCirclesView may only be initialized once.");
        return;
    }


    final ResourceLoader res = new ResourceLoader(context);
    mUnselectedColor = res.getColor(android.R.color.white);
    mSelectedColor = res.getColor(R.color.blue);
    mAmPmTextColor = res.getColor(R.color.ampm_text_color);
    mSelectedAlpha = SELECTED_ALPHA;
    String typefaceFamily = res.getString(R.string.sans_serif);
    Typeface tf = Typeface.create(typefaceFamily, Typeface.NORMAL);
    mPaint.setTypeface(tf);
    mPaint.setAntiAlias(true);
    mPaint.setTextAlign(Align.CENTER);

    mCircleRadiusMultiplier =
            Float.parseFloat(res.getString(R.string.circle_radius_multiplier));
    mAmPmCircleRadiusMultiplier =
            Float.parseFloat(res.getString(R.string.ampm_circle_radius_multiplier));
    String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
    mAmText = amPmTexts[0];
    mPmText = amPmTexts[1];

    setAmOrPm(amOrPm);
    mAmOrPmPressed = -1;

    mIsInitialized = true;
}
 
Example 37
Project: GitHub   File: AmPmCirclesView.java   View source code 5 votes vote down vote up
public void initialize(Context context, int amOrPm) {
    if (mIsInitialized) {
        Log.e(TAG, "AmPmCirclesView may only be initialized once.");
        return;
    }

    Resources res = context.getResources();
    mWhite = res.getColor(R.color.white);
    mAmPmTextColor = res.getColor(R.color.ampm_text_color);
    mBlue = res.getColor(R.color.blue);
    String typefaceFamily = res.getString(R.string.sans_serif);
    Typeface tf = Typeface.create(typefaceFamily, Typeface.NORMAL);
    mPaint.setTypeface(tf);
    mPaint.setAntiAlias(true);
    mPaint.setTextAlign(Align.CENTER);

    mCircleRadiusMultiplier =
            Float.parseFloat(res.getString(R.string.circle_radius_multiplier));
    mAmPmCircleRadiusMultiplier =
            Float.parseFloat(res.getString(R.string.ampm_circle_radius_multiplier));
    String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
    mAmText = amPmTexts[0];
    mPmText = amPmTexts[1];

    setAmOrPm(amOrPm);
    mAmOrPmPressed = -1;

    mIsInitialized = true;
}
 
Example 38
Project: permitlog-android   File: CustomDriveDialog.java   View source code 5 votes vote down vote up
public void setDate(int year, int month, int day) {
    /* This function is called when the user actually picks a date using the dialog setup in the pickDate method. */
    //Set startingTime and endingTime:
    startingTime.set(year, month, day);
    endingTime.set(year, month, day);
    //Get the text of the month:
    String monthText = new DateFormatSymbols().getMonths()[month];
    //Display the date to the user:
    TextView driveDateView = (TextView)findViewById(R.id.drive_date);
    driveDateView.setText(monthText+" "+day+", "+year);
    //Remember to log startingTime and endingTime for debugging:
    Log.d(TAG, "Started driving on: "+startingTime.getTime().toString());
    Log.d(TAG, "Stopped driving on: "+endingTime.getTime().toString());
}
 
Example 39
Project: aos-FileCoreLibrary   File: FTPTimestampParserImpl.java   View source code 5 votes vote down vote up
/**
     * Implementation of the {@link  Configurable  Configurable}
     * interface. Configures this <code>FTPTimestampParser</code> according
     * to the following logic:
     * <p>
     * Set up the {@link  FTPClientConfig#setDefaultDateFormatStr(String) defaultDateFormat}
     * and optionally the {@link  FTPClientConfig#setRecentDateFormatStr(String) recentDateFormat}
     * to values supplied in the config based on month names configured as follows:
     * </p><p><ul>
     * <li>If a {@link  FTPClientConfig#setShortMonthNames(String) shortMonthString}
     * has been supplied in the <code>config</code>, use that to parse  parse timestamps.</li>
     * <li>Otherwise, if a {@link  FTPClientConfig#setServerLanguageCode(String) serverLanguageCode}
     * has been supplied in the <code>config</code>, use the month names represented
     * by that {@link  FTPClientConfig#lookupDateFormatSymbols(String) language}
     * to parse timestamps.</li>
     * <li>otherwise use default English month names</li>
     * </ul></p><p>
     * Finally if a {@link  org.apache.commons.net.ftp.FTPClientConfig#setServerTimeZoneId(String) serverTimeZoneId}
     * has been supplied via the config, set that into all date formats that have
     * been configured.
     * </p>
     */
//    @Override
    public void configure(FTPClientConfig config) {
        DateFormatSymbols dfs = null;

        String languageCode = config.getServerLanguageCode();
        String shortmonths = config.getShortMonthNames();
        if (shortmonths != null) {
            dfs = FTPClientConfig.getDateFormatSymbols(shortmonths);
        } else if (languageCode != null) {
            dfs = FTPClientConfig.lookupDateFormatSymbols(languageCode);
        } else {
            dfs = FTPClientConfig.lookupDateFormatSymbols("en");
        }


        String recentFormatString = config.getRecentDateFormatStr();
        if (recentFormatString == null) {
            this.recentDateFormat = null;
        } else {
            this.recentDateFormat = new SimpleDateFormat(recentFormatString, dfs);
            this.recentDateFormat.setLenient(false);
        }

        String defaultFormatString = config.getDefaultDateFormatStr();
        if (defaultFormatString == null) {
            throw new IllegalArgumentException("defaultFormatString cannot be null");
        }
        this.defaultDateFormat = new SimpleDateFormat(defaultFormatString, dfs);
        this.defaultDateFormat.setLenient(false);

        setServerTimeZone(config.getServerTimeZoneId());

        this.lenientFutureDates = config.isLenientFutureDates();
    }
 
Example 40
Project: aos-FileCoreLibrary   File: FTPClientConfig.java   View source code 5 votes vote down vote up
/**
 * Looks up the supplied language code in the internally maintained table of
 * language codes.  Returns a DateFormatSymbols object configured with
 * short month names corresponding to the code.  If there is no corresponding
 * entry in the table, the object returned will be that for
 * <code>Locale.US</code>
 * @param languageCode See {@link  #setServerLanguageCode(String)  serverLanguageCode}
 * @return a DateFormatSymbols object configured with short month names
 * corresponding to the supplied code, or with month names for
 * <code>Locale.US</code> if there is no corresponding entry in the internal
 * table.
 */
public static DateFormatSymbols lookupDateFormatSymbols(String languageCode)
{
    Object lang = LANGUAGE_CODE_MAP.get(languageCode);
    if (lang != null) {
        if (lang instanceof Locale) {
            return new DateFormatSymbols((Locale) lang);
        } else if (lang instanceof String){
            return getDateFormatSymbols((String) lang);
        }
    }
    return new DateFormatSymbols(Locale.US);
}