Example usage for java.text SimpleDateFormat toPattern

List of usage examples for java.text SimpleDateFormat toPattern

Introduction

In this page you can find the example usage for java.text SimpleDateFormat toPattern.

Prototype

public String toPattern() 

Source Link

Document

Returns a pattern string describing this date format.

Usage

From source file:DateFormatUtils.java

/**
 * <p>Gets a time formatter instance using the specified style, time
 * zone and locale.</p>//from w  ww .  j  ava  2 s.c o  m
 * 
 * @param style  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted time
 * @param locale  optional locale, overrides system locale
 * @return a localized standard time formatter
 * @throws IllegalArgumentException if the Locale has no time
 *  pattern defined
 */
public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) {
    Object key = new Integer(style);
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }
    if (locale != null) {
        key = new Pair(key, locale);
    }

    FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);

        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}

From source file:org.openmrs.util.OpenmrsUtilTest.java

/**
 * @see OpenmrsUtil#getDateFormat(Locale)
 *//*ww  w  . j  a  va 2 s.c o  m*/
@Test
public void getDateFormat_shouldNotAllowTheReturnedSimpleDateFormatToBeModified() {
    // start with a locale that is not currently cached by getDateFormat()
    Locale locale = new Locale("hk");
    Assert.assertTrue("default locale is potentially already cached", !Context.getLocale().equals(locale));

    // get the initially built dateformat from getDateFormat()
    SimpleDateFormat sdf = OpenmrsUtil.getDateFormat(locale);
    Assert.assertNotSame("initial dateFormatCache entry is modifiable", OpenmrsUtil.getDateFormat(locale), sdf);

    // verify changing the pattern on our variable does not affect the cache
    sdf.applyPattern("yyyymmdd");
    Assert.assertTrue("initial dateFormatCache pattern is modifiable",
            !OpenmrsUtil.getDateFormat(locale).toPattern().equals(sdf.toPattern()));

    // the dateformat cache now contains the format for this locale; checking
    // a second time will guarantee we are looking at cached data and not the
    // initially built dateformat
    sdf = OpenmrsUtil.getDateFormat(locale);
    Assert.assertNotSame("cached dateFormatCache entry is modifiable", OpenmrsUtil.getDateFormat(locale), sdf);

    // verify changing the pattern on our variable does not affect the cache
    sdf.applyPattern("yyyymmdd");
    Assert.assertTrue("cached dateFormatCache pattern is modifiable",
            !OpenmrsUtil.getDateFormat(locale).toPattern().equals(sdf.toPattern()));
}

From source file:ca.sqlpower.wabit.dao.WorkspaceXMLDAO.java

/**
 * This saves a layout. This will not close the print writer passed into the constructor.
 * If this save method is used to export the query cache somewhere then close should be 
 * called on it to flush the print writer and close it.
 *//*from   ww  w .  j a va2s  . c om*/
private void saveLayout(Layout layout) {
    xml.print(out, "<layout");
    printCommonAttributes(layout);
    printAttribute("zoom", layout.getZoomLevel());
    printAttribute("template", (layout instanceof Template));
    xml.niprintln(out, ">");
    xml.indent++;

    Page page = layout.getPage();
    xml.print(out, "<layout-page");
    printCommonAttributes(page);
    printAttribute("height", page.getHeight());
    printAttribute("width", page.getWidth());
    printAttribute("orientation", page.getOrientation().name());
    xml.niprintln(out, ">");
    xml.indent++;
    saveFont(page.getDefaultFont());

    if (layout instanceof Report) {
        for (Selector selector : ((Report) layout).getSelectors()) {
            saveSelector(selector);
        }
    }

    for (WabitObject object : page.getChildren()) {
        if (object instanceof ContentBox) {
            ContentBox box = (ContentBox) object;
            xml.print(out, "<content-box");
            printCommonAttributes(box);
            printAttribute("width", box.getWidth());
            printAttribute("height", box.getHeight());
            printAttribute("xpos", box.getX());
            printAttribute("ypos", box.getY());
            xml.niprintln(out, ">");
            xml.indent++;
            saveFont(box.getFont());

            // Save ContentBox selectors.
            for (Selector selector : box.getChildren(Selector.class)) {
                saveSelector(selector);
            }

            if (box.getContentRenderer() != null) {
                if (box.getContentRenderer() instanceof WabitLabel) {
                    WabitLabel label = (WabitLabel) box.getContentRenderer();
                    xml.print(out, "<content-label");
                    printCommonAttributes(label);
                    printAttribute("horizontal-align", label.getHorizontalAlignment().name());
                    printAttribute("vertical-align", label.getVerticalAlignment().name());
                    if (label.getBackgroundColour() != null) {
                        printAttribute("bg-colour", label.getBackgroundColour().getRGB());
                    }
                    xml.niprintln(out, ">");
                    xml.indent++;
                    xml.print(out, "<text>");
                    xml.niprint(out, SQLPowerUtils.escapeXML(label.getText()));
                    xml.niprintln(out, "</text>");
                    saveFont(label.getFont());
                    xml.indent--;
                    xml.println(out, "</content-label>");
                } else if (box.getContentRenderer() instanceof ResultSetRenderer) {
                    ResultSetRenderer rsRenderer = (ResultSetRenderer) box.getContentRenderer();
                    xml.print(out, "<content-result-set");
                    printCommonAttributes(rsRenderer);
                    printAttribute("query-id", rsRenderer.getContent().getUUID());
                    printAttribute("null-string", rsRenderer.getNullString());
                    printAttribute("border", rsRenderer.getBorderType().name());
                    printAttribute("grand-totals", rsRenderer.isPrintingGrandTotals());
                    if (rsRenderer.getBackgroundColour() != null) {
                        printAttribute("bg-colour", rsRenderer.getBackgroundColour().getRGB());
                    }
                    printAttribute("header-colour", rsRenderer.getHeaderColour().getRGB());
                    printAttribute("data-colour", rsRenderer.getDataColour().getRGB());
                    xml.niprintln(out, ">");
                    xml.indent++;
                    saveFont(rsRenderer.getHeaderFont(), "header-font");
                    saveFont(rsRenderer.getBodyFont(), "body-font");
                    for (WabitObject rendererChild : rsRenderer.getChildren()) {
                        ColumnInfo ci = (ColumnInfo) rendererChild;
                        xml.print(out, "<column-info");
                        printCommonAttributes(ci);
                        printAttribute("width", ci.getWidth());
                        if (ci.getColumnInfoItem() != null) {
                            printAttribute("column-info-item-id", ci.getColumnInfoItem().getUUID());
                        }
                        printAttribute("column-alias", ci.getColumnAlias());
                        printAttribute("horizontal-align", ci.getHorizontalAlignment().name());
                        printAttribute("data-type", ci.getDataType().name());
                        printAttribute("group-or-break", ci.getWillGroupOrBreak().name());
                        printAttribute("will-subtotal", Boolean.toString(ci.getWillSubtotal()));
                        xml.niprintln(out, ">");
                        xml.indent++;
                        if (ci.getFormat() instanceof SimpleDateFormat) {
                            xml.print(out, "<date-format");
                            SimpleDateFormat dateFormat = (SimpleDateFormat) ci.getFormat();
                            printAttribute("format", dateFormat.toPattern());
                            xml.niprintln(out, "/>");
                        } else if (ci.getFormat() instanceof DecimalFormat) {
                            xml.print(out, "<decimal-format");
                            DecimalFormat decimalFormat = (DecimalFormat) ci.getFormat();
                            printAttribute("format", decimalFormat.toPattern());
                            xml.niprintln(out, "/>");
                        } else if (ci.getFormat() == null) {
                            // This is a default format
                        } else {
                            throw new ClassCastException("Cannot cast format of type "
                                    + ci.getFormat().getClass() + " to a known format type when saving.");
                        }
                        xml.indent--;
                        xml.println(out, "</column-info>");
                    }
                    xml.indent--;
                    xml.println(out, "</content-result-set>");
                } else if (box.getContentRenderer() instanceof ImageRenderer) {
                    ImageRenderer imgRenderer = (ImageRenderer) box.getContentRenderer();
                    xml.print(out, "<image-renderer");
                    printCommonAttributes(imgRenderer);
                    if (imgRenderer.getImage() != null) {
                        printAttribute("wabit-image-uuid", imgRenderer.getImage().getUUID());
                    }
                    printAttribute("preserving-aspect-ratio", imgRenderer.isPreservingAspectRatio());
                    printAttribute("h-align", imgRenderer.getHAlign().name());
                    printAttribute("v-align", imgRenderer.getVAlign().name());
                    xml.niprint(out, ">");
                    out.println("</image-renderer>");

                } else if (box.getContentRenderer() instanceof ChartRenderer) {
                    ChartRenderer chartRenderer = (ChartRenderer) box.getContentRenderer();
                    xml.print(out, "<chart-renderer");
                    printCommonAttributes(chartRenderer);
                    printAttribute("chart-uuid", chartRenderer.getContent().getUUID());
                    xml.println(out, " />");

                } else if (box.getContentRenderer() instanceof CellSetRenderer) {
                    CellSetRenderer renderer = (CellSetRenderer) box.getContentRenderer();
                    xml.print(out, "<cell-set-renderer");
                    printCommonAttributes(renderer);
                    printAttribute("olap-query-uuid", renderer.getContent().getUUID());
                    printAttribute("body-alignment", renderer.getBodyAlignment().toString());
                    if (renderer.getBodyFormat() != null) {
                        printAttribute("body-format-pattern", renderer.getBodyFormat().toPattern());
                    }
                    xml.println(out, ">");
                    xml.indent++;

                    saveFont(renderer.getHeaderFont(), "olap-header-font");
                    saveFont(renderer.getBodyFont(), "olap-body-font");

                    this.saveOlapQuery(renderer.getModifiedOlapQuery());

                    xml.indent--;
                    xml.println(out, "</cell-set-renderer>");

                } else {
                    throw new ClassCastException(
                            "Cannot save a content renderer of class " + box.getContentRenderer().getClass());
                }
            }

            xml.indent--;
            xml.println(out, "</content-box>");
        } else if (object instanceof Guide) {
            Guide guide = (Guide) object;
            xml.print(out, "<guide");
            printCommonAttributes(guide);
            printAttribute("axis", guide.getAxis().name());
            printAttribute("offset", guide.getOffset());
            xml.niprintln(out, "/>");
        } else {
            throw new ClassCastException("Cannot save page element of type " + object.getClass());
        }
    }

    xml.indent--;
    xml.println(out, "</layout-page>");

    xml.indent--;
    xml.println(out, "</layout>");
}

From source file:DateFormatUtils.java

/**
 * <p>Gets a date/time formatter instance using the specified style,
 * time zone and locale.</p>/*from www.  j  a  v  a 2s  .co m*/
 * 
 * @param dateStyle  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeStyle  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted date
 * @param locale  optional locale, overrides system locale
 * @return a localized standard date/time formatter
 * @throws IllegalArgumentException if the Locale has no date/time
 *  pattern defined
 */
public static synchronized FastDateFormat getDateTimeInstance(int dateStyle, int timeStyle, TimeZone timeZone,
        Locale locale) {

    Object key = new Pair(new Integer(dateStyle), new Integer(timeStyle));
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    key = new Pair(key, locale);

    FastDateFormat format = (FastDateFormat) cDateTimeInstanceCache.get(key);
    if (format == null) {
        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateTimeInstance(dateStyle, timeStyle,
                    locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateTimeInstanceCache.put(key, format);

        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date time pattern for locale: " + locale);
        }
    }
    return format;
}

From source file:org.sakaiproject.cheftool.VelocityPortletPaneledAction.java

public String[] getDateFormatString() {
    SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, rb.getLocale());
    String[] formatArray = sdf.toPattern().split("[/\\-\\.]");
    for (int i = 0; i < formatArray.length; i++)
        formatArray[i] = formatArray[i].trim().substring(0, 1).toLowerCase();

    if (formatArray.length != DEFAULT_FORMAT_ARRAY.length) {
        M_log.warn("Unknown date format string (using default): " + sdf.toPattern());
        return DEFAULT_FORMAT_ARRAY;
    } else {/*from  www  . ja  v  a  2 s.c o  m*/
        return formatArray;
    }
}

From source file:org.sakaiproject.cheftool.VelocityPortletPaneledAction.java

/**
 ** Return a String array containing the "h", "m", "a", or "H" characters (corresponding to hour, minute, am/pm, or 24-hour)
 ** in the locale specific order//from w w w. ja  va2  s  .co m
 **/
public String[] getTimeFormatString() {
    SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT, rb.getLocale());
    String format = sdf.toPattern();

    Set<String> formatSet = new LinkedHashSet<String>();
    char curChar;
    char lastChar = 0;
    for (int i = 0; i < format.length(); i++) {
        curChar = format.charAt(i);
        if ((curChar == 'h' || curChar == 'm' || curChar == 'a' || curChar == 'H') && curChar != lastChar) {
            formatSet.add(String.valueOf(curChar));
            lastChar = curChar;
        }
    }

    String[] formatArray = formatSet.toArray(new String[formatSet.size()]);
    if (formatArray.length != DEFAULT_TIME_FORMAT_ARRAY.length
            && formatArray.length != DEFAULT_TIME_FORMAT_ARRAY.length - 1) {
        M_log.warn("Unknown time format string (using default): " + format);
        return DEFAULT_TIME_FORMAT_ARRAY.clone();
    } else {
        return formatArray;
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get the current user's time format Will look similar to "hh:mm a". Depends on user's locale.
 * /*  www  .  j  a  v  a 2  s  .c o  m*/
 * @return a simple time format
 * @should return a pattern with two h characters in it
 * @should not allow the returned SimpleDateFormat to be modified
 * @since 1.9
 */
public static SimpleDateFormat getTimeFormat(Locale locale) {
    if (timeFormatCache.containsKey(locale)) {
        return (SimpleDateFormat) timeFormatCache.get(locale).clone();
    }

    SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    String pattern = sdf.toPattern();

    if (!(pattern.contains("hh") || pattern.contains("HH"))) {
        // otherwise, change the pattern to be a two digit hour
        pattern = pattern.replaceFirst("h", "hh").replaceFirst("H", "HH");
        sdf.applyPattern(pattern);
    }

    timeFormatCache.put(locale, sdf);

    return (SimpleDateFormat) sdf.clone();
}

From source file:org.mifos.application.servicefacade.SavingsServiceFacadeWebTier.java

@Override
public void updateSavingsAccountDetails(Long savingsId, String recommendedOrMandatoryAmount,
        List<CustomFieldDto> customFields) {

    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    SavingsBO savingsAccount = this.savingsDao.findById(savingsId);
    savingsAccount.updateDetails(userContext);

    Set<AccountCustomFieldEntity> accountCustomFields = savingsAccount.getAccountCustomFields();
    for (CustomFieldDto view : customFields) {
        boolean fieldPresent = false;
        if (CustomFieldType.DATE.getValue().equals(view.getFieldType())
                && org.apache.commons.lang.StringUtils.isNotBlank(view.getFieldValue())) {
            try {
                SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                        userContext.getPreferredLocale());
                String userfmt = DateUtils.convertToCurrentDateFormat(format.toPattern());
                view.setFieldValue(DateUtils.convertUserToDbFmt(view.getFieldValue(), userfmt));
            } catch (InvalidDateException e) {
                throw new BusinessRuleException(e.getMessage(), e);
            }// ww  w  .  j  a  v a  2  s .co  m
        }
        for (AccountCustomFieldEntity customFieldEntity : accountCustomFields) {
            if (customFieldEntity.getFieldId().equals(view.getFieldId())) {
                fieldPresent = true;
                customFieldEntity.setFieldValue(view.getFieldValue());
            }
        }
        if (!fieldPresent) {
            accountCustomFields
                    .add(new AccountCustomFieldEntity(savingsAccount, view.getFieldId(), view.getFieldValue()));
        }
    }

    Money amount = new Money(savingsAccount.getCurrency(), recommendedOrMandatoryAmount);

    try {
        this.transactionHelper.startTransaction();
        this.transactionHelper.beginAuditLoggingFor(savingsAccount);

        savingsAccount.update(amount, accountCustomFields);

        this.savingsDao.save(savingsAccount);
        this.transactionHelper.commitTransaction();
    } catch (BusinessRuleException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getMessageKey(), e);
    } catch (Exception e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } finally {
        this.transactionHelper.closeSession();
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get the current user's datetime format Will look similar to "mm-dd-yyyy hh:mm a". Depends on
 * user's locale./* ww  w.j  av  a 2 s  .  c o  m*/
 * 
 * @return a simple date format
 * @should return a pattern with four y characters and two h characters in it
 * @should not allow the returned SimpleDateFormat to be modified
 * @since 1.9
 */
public static SimpleDateFormat getDateTimeFormat(Locale locale) {
    SimpleDateFormat dateFormat;
    SimpleDateFormat timeFormat;

    dateFormat = getDateFormat(locale);
    timeFormat = getTimeFormat(locale);

    String pattern = dateFormat.toPattern() + " " + timeFormat.toPattern();
    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.applyPattern(pattern);
    return sdf;
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get the current user's date format Will look similar to "mm-dd-yyyy". Depends on user's
 * locale./*from   w  ww  .ja  v a2  s. co  m*/
 * 
 * @return a simple date format
 * @should return a pattern with four y characters in it
 * @should not allow the returned SimpleDateFormat to be modified
 * @since 1.5
 */
public static SimpleDateFormat getDateFormat(Locale locale) {
    if (dateFormatCache.containsKey(locale)) {
        return (SimpleDateFormat) dateFormatCache.get(locale).clone();
    }

    // note that we are using the custom OpenmrsDateFormat class here which prevents erroneous parsing of 2-digit years
    SimpleDateFormat sdf = new OpenmrsDateFormat(
            (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale), locale);
    String pattern = sdf.toPattern();

    if (!pattern.contains("yyyy")) {
        // otherwise, change the pattern to be a four digit year
        pattern = pattern.replaceFirst("yy", "yyyy");
        sdf.applyPattern(pattern);
    }
    if (!pattern.contains("MM")) {
        // change the pattern to be a two digit month
        pattern = pattern.replaceFirst("M", "MM");
        sdf.applyPattern(pattern);
    }
    if (!pattern.contains("dd")) {
        // change the pattern to be a two digit day
        pattern = pattern.replaceFirst("d", "dd");
        sdf.applyPattern(pattern);
    }

    dateFormatCache.put(locale, sdf);

    return (SimpleDateFormat) sdf.clone();
}